code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" 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 lowercase ( lowerCAmelCase__ : Tuple ) -> str: if is_torch_version('''<''' , '''2.0.0''' ) or not hasattr(lowerCAmelCase__ , '''_dynamo''' ): return False return isinstance(lowerCAmelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : bool = True ) -> int: __a = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) __a = is_compiled_module(lowerCAmelCase__ ) if is_compiled: __a = model __a = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = model.module if not keep_fpaa_wrapper: __a = getattr(lowerCAmelCase__ , '''forward''' ) __a = model.__dict__.pop('''_original_forward''' , lowerCAmelCase__ ) if original_forward is not None: while hasattr(lowerCAmelCase__ , '''__wrapped__''' ): __a = forward.__wrapped__ if forward == original_forward: break __a = forward if getattr(lowerCAmelCase__ , '''_converted_to_transformer_engine''' , lowerCAmelCase__ ): convert_model(lowerCAmelCase__ , to_transformer_engine=lowerCAmelCase__ ) if is_compiled: __a = model __a = compiled_model return model def lowercase ( ) -> Optional[int]: PartialState().wait_for_everyone() def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple ) -> int: if PartialState().distributed_type == DistributedType.TPU: xm.save(lowerCAmelCase__ , lowerCAmelCase__ ) elif PartialState().local_process_index == 0: torch.save(lowerCAmelCase__ , lowerCAmelCase__ ) @contextmanager def lowercase ( **lowerCAmelCase__ : List[str] ) -> List[str]: for key, value in kwargs.items(): __a = str(lowerCAmelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowercase ( lowerCAmelCase__ : Any ) -> Optional[int]: if not hasattr(lowerCAmelCase__ , '''__qualname__''' ) and not hasattr(lowerCAmelCase__ , '''__name__''' ): __a = getattr(lowerCAmelCase__ , '''__class__''' , lowerCAmelCase__ ) if hasattr(lowerCAmelCase__ , '''__qualname__''' ): return obj.__qualname__ if hasattr(lowerCAmelCase__ , '''__name__''' ): return obj.__name__ return str(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] ) -> str: for key, value in source.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = destination.setdefault(lowerCAmelCase__ , {} ) merge_dicts(lowerCAmelCase__ , lowerCAmelCase__ ) else: __a = value return destination def lowercase ( lowerCAmelCase__ : int = None ) -> bool: if port is None: __a = 29500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('''localhost''', port) ) == 0
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = self._index.query(_a ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(_a , _a ) if len(_a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_a ) break else: self._duplicate_clusters[close_duplicates[0]].add(_a ) def __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase__ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__ ) ) , max_queue_size=100 ) ): di.add(lowerCAmelCase__ , lowerCAmelCase__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCAmelCase__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCAmelCase__ , lowerCAmelCase__ , ) , total=len(lowerCAmelCase__ ) , ): extremes_list.append(lowerCAmelCase__ ) return extremes_list def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = dataset.filter(lambda lowerCAmelCase__ , lowerCAmelCase__ : idx not in remove_indices , with_indices=lowerCAmelCase__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = extreme_dict[element['''base_index''']]['''copies'''] print(f'''Original dataset size: {len(lowerCAmelCase__ )}''' ) print(f'''Number of duplicate clusters: {len(lowerCAmelCase__ )}''' ) print(f'''Files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Unique files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Filtered dataset size: {len(lowerCAmelCase__ )}''' ) return ds_filter, duplicate_clusters
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> int: return int((input_a, input_a).count(1 ) != 0 ) def lowercase ( ) -> None: assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "adapter_layer": "encoder.layers.*.adapter_layer", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", "pooling_layer.linear": "projector", "pooling_layer.projection": "classifier", } lowercase_ = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "projector", "classifier", ] def lowercase ( lowerCAmelCase__ : Dict ) -> Union[str, Any]: __a = {} with open(lowerCAmelCase__ , '''r''' ) as file: for line_number, line in enumerate(lowerCAmelCase__ ): __a = line.strip() if line: __a = line.split() __a = line_number __a = words[0] __a = value return result def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Union[str, Any]: for attribute in key.split('''.''' ): __a = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) __a = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowerCAmelCase__ ): __a = PARAM_MAPPING[full_name.split('''.''' )[-1]] __a = '''param''' if weight_type is not None and weight_type != "param": __a = getattr(lowerCAmelCase__ , lowerCAmelCase__ ).shape elif weight_type is not None and weight_type == "param": __a = hf_pointer for attribute in hf_param_name.split('''.''' ): __a = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) __a = shape_pointer.shape # let's reduce dimension __a = value[0] else: __a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": __a = value elif weight_type == "weight_g": __a = value elif weight_type == "weight_v": __a = value elif weight_type == "bias": __a = value elif weight_type == "param": for attribute in hf_param_name.split('''.''' ): __a = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) __a = value else: __a = value logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : int , lowerCAmelCase__ : Any ) -> Any: __a = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowerCAmelCase__ ): __a = PARAM_MAPPING[full_name.split('''.''' )[-1]] __a = '''param''' if weight_type is not None and weight_type != "param": __a = '''.'''.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __a = '''.'''.join([key, hf_param_name] ) else: __a = key __a = value if '''lm_head''' in full_key else value[0] lowercase_ = { "W_a": "linear_1.weight", "W_b": "linear_2.weight", "b_a": "linear_1.bias", "b_b": "linear_2.bias", "ln_W": "norm.weight", "ln_b": "norm.bias", } def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : Union[str, Any]=None ) -> List[Any]: __a = False for key, mapped_key in MAPPING.items(): __a = '''wav2vec2.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __a = True if "*" in mapped_key: __a = name.split(lowerCAmelCase__ )[0].split('''.''' )[-2] __a = mapped_key.replace('''*''' , lowerCAmelCase__ ) if "weight_g" in name: __a = '''weight_g''' elif "weight_v" in name: __a = '''weight_v''' elif "bias" in name: __a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __a = '''weight''' else: __a = None if hf_dict is not None: rename_dict(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) else: set_recursively(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return is_used return is_used def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Union[str, Any] ) -> Dict: __a = [] __a = fairseq_model.state_dict() __a = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __a = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , hf_model.config.feat_extract_norm == '''group''' , ) __a = True else: __a = load_wavaveca_layer(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: __a = full_name.split('''conv_layers.''' )[-1] __a = name.split('''.''' ) __a = int(items[0] ) __a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) __a = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) __a = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) __a = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) __a = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowerCAmelCase__ ) @torch.no_grad() def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int=None , lowerCAmelCase__ : Optional[Any]=None , lowerCAmelCase__ : Dict=True , lowerCAmelCase__ : int=False ) -> Optional[Any]: if config_path is not None: __a = WavaVecaConfig.from_pretrained(lowerCAmelCase__ ) else: __a = WavaVecaConfig() if is_seq_class: __a = read_txt_into_dict(lowerCAmelCase__ ) __a = idalabel __a = WavaVecaForSequenceClassification(lowerCAmelCase__ ) __a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , ) feature_extractor.save_pretrained(lowerCAmelCase__ ) elif is_finetuned: if dict_path: __a = Dictionary.load(lowerCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __a = target_dict.pad_index __a = target_dict.bos_index __a = target_dict.eos_index __a = len(target_dict.symbols ) __a = os.path.join(lowerCAmelCase__ , '''vocab.json''' ) if not os.path.isdir(lowerCAmelCase__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowerCAmelCase__ ) ) return os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) __a = target_dict.indices # fairseq has the <pad> and <s> switched __a = 0 __a = 1 with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) __a = WavaVecaCTCTokenizer( lowerCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=lowerCAmelCase__ , ) __a = True if config.feat_extract_norm == '''layer''' else False __a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , ) __a = WavaVecaProcessor(feature_extractor=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) __a = WavaVecaForCTC(lowerCAmelCase__ ) else: __a = WavaVecaForPreTraining(lowerCAmelCase__ ) if is_finetuned or is_seq_class: __a , __a , __a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __a = argparse.Namespace(task='''audio_pretraining''' ) __a = fairseq.tasks.setup_task(lowerCAmelCase__ ) __a , __a , __a = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowerCAmelCase__ ) __a = model[0].eval() recursively_load_weights(lowerCAmelCase__ , lowerCAmelCase__ , not is_finetuned ) hf_wavavec.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) parser.add_argument( "--is_seq_class", action="store_true", help="Whether the model to convert is a fine-tuned sequence classification model or not", ) lowercase_ = parser.parse_args() lowercase_ = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
45
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
1
"""simple docstring""" class __lowerCAmelCase : # Public class to implement a graph '''simple docstring''' def __init__( self , _a , _a , _a ): __a = row __a = col __a = graph def __UpperCAmelCase ( self , _a , _a , _a ): return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def __UpperCAmelCase ( self , _a , _a , _a ): # Checking all 8 elements surrounding nth element __a = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order __a = [-1, 0, 1, -1, 1, -1, 0, 1] __a = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , _a ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , _a ) def __UpperCAmelCase ( self ): # And finally, count all islands. __a = [[False for j in range(self.COL )] for i in range(self.ROW )] __a = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(_a , _a , _a ) count += 1 return count
45
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
1
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def lowercase ( lowerCAmelCase__ : int ) -> Optional[int]: # vision encoder if "img_encoder.pos_embed" in name: __a = name.replace('''img_encoder.pos_embed''' , '''vision_model.embeddings.position_embeddings''' ) if "img_encoder.patch_embed.proj" in name: __a = name.replace('''img_encoder.patch_embed.proj''' , '''vision_model.embeddings.patch_embeddings.projection''' ) if "img_encoder.patch_embed.norm" in name: __a = name.replace('''img_encoder.patch_embed.norm''' , '''vision_model.embeddings.layernorm''' ) if "img_encoder.layers" in name: __a = name.replace('''img_encoder.layers''' , '''vision_model.encoder.stages''' ) if "blocks" in name and "res" not in name: __a = name.replace('''blocks''' , '''layers''' ) if "attn" in name and "pre_assign" not in name: __a = name.replace('''attn''' , '''self_attn''' ) if "proj" in name and "self_attn" in name and "text" not in name: __a = name.replace('''proj''' , '''out_proj''' ) if "pre_assign_attn.attn.proj" in name: __a = name.replace('''pre_assign_attn.attn.proj''' , '''pre_assign_attn.attn.out_proj''' ) if "norm1" in name: __a = name.replace('''norm1''' , '''layer_norm1''' ) if "norm2" in name and "pre_assign" not in name: __a = name.replace('''norm2''' , '''layer_norm2''' ) if "img_encoder.norm" in name: __a = name.replace('''img_encoder.norm''' , '''vision_model.layernorm''' ) # text encoder if "text_encoder.token_embedding" in name: __a = name.replace('''text_encoder.token_embedding''' , '''text_model.embeddings.token_embedding''' ) if "text_encoder.positional_embedding" in name: __a = name.replace('''text_encoder.positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "text_encoder.transformer.resblocks." in name: __a = name.replace('''text_encoder.transformer.resblocks.''' , '''text_model.encoder.layers.''' ) if "ln_1" in name: __a = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: __a = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: __a = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: __a = name.replace('''c_proj''' , '''fc2''' ) if "text_encoder" in name: __a = name.replace('''text_encoder''' , '''text_model''' ) if "ln_final" in name: __a = name.replace('''ln_final''' , '''final_layer_norm''' ) # projection layers if "img_projector.linear_hidden." in name: __a = name.replace('''img_projector.linear_hidden.''' , '''visual_projection.''' ) if "img_projector.linear_out." in name: __a = name.replace('''img_projector.linear_out.''' , '''visual_projection.3.''' ) if "text_projector.linear_hidden" in name: __a = name.replace('''text_projector.linear_hidden''' , '''text_projection''' ) if "text_projector.linear_out" in name: __a = name.replace('''text_projector.linear_out''' , '''text_projection.3''' ) return name def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> int: for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(lowerCAmelCase__ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors __a = key.split('''.''' ) __a , __a = int(key_split[2] ), int(key_split[4] ) __a = config.vision_config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[dim : dim * 2, :] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors __a = key.split('''.''' ) __a = int(key_split[3] ) __a = config.text_config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[ dim : dim * 2, : ] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] else: __a = rename_key(lowerCAmelCase__ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): __a = val.squeeze_() else: __a = val return orig_state_dict def lowercase ( ) -> Tuple: __a = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __a = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any="groupvit-gcc-yfcc" , lowerCAmelCase__ : List[str]=False ) -> Optional[Any]: __a = GroupViTConfig() __a = GroupViTModel(lowerCAmelCase__ ).eval() __a = torch.load(lowerCAmelCase__ , map_location='''cpu''' )['''model'''] __a = convert_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) __a , __a = model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowerCAmelCase__ ) == 0) # verify result __a = CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) __a = prepare_img() __a = processor(text=['''a photo of a cat''', '''a photo of a dog'''] , images=lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors='''pt''' ) with torch.no_grad(): __a = model(**lowerCAmelCase__ ) if model_name == "groupvit-gcc-yfcc": __a = torch.tensor([[13.35_23, 6.36_29]] ) elif model_name == "groupvit-gcc-redcaps": __a = torch.tensor([[16.18_73, 8.62_30]] ) else: raise ValueError(f'''Model name {model_name} not supported.''' ) assert torch.allclose(outputs.logits_per_image , lowerCAmelCase__ , atol=1e-3 ) processor.save_pretrained(lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) print('''Successfully saved processor and model to''' , lowerCAmelCase__ ) if push_to_hub: print('''Pushing to the hub...''' ) processor.push_to_hub(lowerCAmelCase__ , organization='''nielsr''' ) model.push_to_hub(lowerCAmelCase__ , organization='''nielsr''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to dump the processor and PyTorch model." ) parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to GroupViT checkpoint") parser.add_argument( "--model_name", default="groupvit-gccy-fcc", type=str, help="Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.", ) lowercase_ = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
45
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowercase_ = False class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a=32 ): set_seed(0 ) __a = UNetaDModel(sample_size=_a , in_channels=3 , out_channels=3 ) __a = torch.optim.SGD(model.parameters() , lr=0.0001 ) return model, optimizer @slow def __UpperCAmelCase ( self ): __a = '''cpu''' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable __a = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=_a , ) __a = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=_a , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) __a = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(_a ) for _ in range(4 )] __a = [torch.randn((4, 3, 32, 32) ).to(_a ) for _ in range(4 )] __a = [torch.randint(0 , 1_000 , (4,) ).long().to(_a ) for _ in range(4 )] # train with a DDPM scheduler __a , __a = self.get_model_optimizer(resolution=32 ) model.train().to(_a ) for i in range(4 ): optimizer.zero_grad() __a = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) __a = model(_a , timesteps[i] ).sample __a = torch.nn.functional.mse_loss(_a , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM __a , __a = self.get_model_optimizer(resolution=32 ) model.train().to(_a ) for i in range(4 ): optimizer.zero_grad() __a = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) __a = model(_a , timesteps[i] ).sample __a = torch.nn.functional.mse_loss(_a , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(_a , _a , atol=1E-5 ) ) self.assertTrue(torch.allclose(_a , _a , atol=1E-5 ) )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ : str ) -> Optional[Any]: __a = '''huggingface/label-files''' __a = '''imagenet-1k-id2label.json''' __a = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) __a = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} __a = {v: k for k, v in idalabel.items()} __a = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" __a = BitConfig( conv_layer=lowerCAmelCase__ , num_labels=1000 , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , ) return config def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> List[Any]: if "stem.conv" in name: __a = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: __a = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: __a = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): __a = '''bit.''' + name if "bit" not in name and "classifier" not in name: __a = '''bit.encoder.''' + name return name def lowercase ( ) -> List[Any]: __a = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __a = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any]=False ) -> Dict: __a = get_config(lowerCAmelCase__ ) # load original model from timm __a = create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ) timm_model.eval() # load state_dict of original model __a = timm_model.state_dict() for key in state_dict.copy().keys(): __a = state_dict.pop(lowerCAmelCase__ ) __a = val.squeeze() if '''head''' in key else val # load HuggingFace model __a = BitForImageClassification(lowerCAmelCase__ ) model.eval() model.load_state_dict(lowerCAmelCase__ ) # create image processor __a = create_transform(**resolve_data_config({} , model=lowerCAmelCase__ ) ) __a = transform.transforms __a = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } __a = BitImageProcessor( do_resize=lowerCAmelCase__ , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowerCAmelCase__ , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=lowerCAmelCase__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) __a = prepare_img() __a = transform(lowerCAmelCase__ ).unsqueeze(0 ) __a = processor(lowerCAmelCase__ , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ) # verify logits with torch.no_grad(): __a = model(lowerCAmelCase__ ) __a = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) __a = timm_model(lowerCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase__ , outputs.logits , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) print(f'''Saving model {model_name} and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(f'''Pushing model {model_name} and processor to the hub''' ) model.push_to_hub(f'''ybelkada/{model_name}''' ) processor.push_to_hub(f'''ybelkada/{model_name}''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="resnetv2_50x1_bitm", type=str, help="Name of the BiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model to the hub.", ) lowercase_ = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
45
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
1
"""simple docstring""" import doctest from collections import deque import numpy as np class __lowerCAmelCase : '''simple docstring''' def __init__( self ): __a = [2, 1, 2, -1] __a = [1, 2, 3, 4] def __UpperCAmelCase ( self ): __a = len(self.first_signal ) __a = len(self.second_signal ) __a = max(_a , _a ) # create a zero matrix of max_length x max_length __a = [[0] * max_length for i in range(_a )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(_a ): __a = deque(self.second_signal ) rotated_signal.rotate(_a ) for j, item in enumerate(_a ): matrix[i][j] += item # multiply the matrix with the first signal __a = np.matmul(np.transpose(_a ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(_a , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
45
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
1
"""simple docstring""" from typing import Dict, Iterable, Optional, 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, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract lowercase_ = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Optional[str] , lowerCAmelCase__ : Optional[str] ) -> str: __a = to_pil_image(lowerCAmelCase__ ) __a , __a = pil_image.size __a = pytesseract.image_to_data(lowerCAmelCase__ , lang=lowerCAmelCase__ , output_type='''dict''' , config=lowerCAmelCase__ ) __a , __a , __a , __a , __a = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates __a = [idx for idx, word in enumerate(lowerCAmelCase__ ) if not word.strip()] __a = [word for idx, word in enumerate(lowerCAmelCase__ ) if idx not in irrelevant_indices] __a = [coord for idx, coord in enumerate(lowerCAmelCase__ ) if idx not in irrelevant_indices] __a = [coord for idx, coord in enumerate(lowerCAmelCase__ ) if idx not in irrelevant_indices] __a = [coord for idx, coord in enumerate(lowerCAmelCase__ ) if idx not in irrelevant_indices] __a = [coord for idx, coord in enumerate(lowerCAmelCase__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format __a = [] for x, y, w, h in zip(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): __a = [x, y, x + w, y + h] actual_boxes.append(lowerCAmelCase__ ) # finally, normalize the bounding boxes __a = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) ) assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['pixel_values'] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , _a = True , _a = None , _a = "" , **_a , ): super().__init__(**_a ) __a = size if size is not None else {'''height''': 224, '''width''': 224} __a = get_size_dict(_a ) __a = do_resize __a = size __a = resample __a = do_rescale __a = rescale_value __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __a = image_std if image_std is not None else IMAGENET_STANDARD_STD __a = apply_ocr __a = ocr_lang __a = tesseract_config def __UpperCAmelCase ( self , _a , _a , _a = PILImageResampling.BILINEAR , _a = None , **_a , ): __a = get_size_dict(_a ) 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()}''' ) __a = (size['''height'''], size['''width''']) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def __UpperCAmelCase ( self , _a , _a , _a = None , **_a , ): return rescale(_a , scale=_a , data_format=_a , **_a ) def __UpperCAmelCase ( self , _a , _a , _a , _a = None , **_a , ): return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def __UpperCAmelCase ( self , _a , _a = None , _a = None , _a=None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(_a ) __a = resample if resample is not None else self.resample __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = apply_ocr if apply_ocr is not None else self.apply_ocr __a = ocr_lang if ocr_lang is not None else self.ocr_lang __a = tesseract_config if tesseract_config is not None else self.tesseract_config __a = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size 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('''If do_normalize is True, image_mean and image_std must be specified.''' ) # All transformations expect numpy arrays. __a = [to_numpy_array(_a ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , '''pytesseract''' ) __a = [] __a = [] for image in images: __a , __a = apply_tesseract(_a , _a , _a ) words_batch.append(_a ) boxes_batch.append(_a ) if do_resize: __a = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_rescale: __a = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: __a = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] __a = [to_channel_dimension_format(_a , _a ) for image in images] __a = BatchFeature(data={'''pixel_values''': images} , tensor_type=_a ) if apply_ocr: __a = words_batch __a = boxes_batch return data
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
1
"""simple docstring""" import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) lowercase_ = logging.getLogger(__name__) lowercase_ = tf.data.AUTOTUNE def lowercase ( ) -> Optional[int]: __a = argparse.ArgumentParser(description='''Train a masked language model on TPU.''' ) parser.add_argument( '''--pretrained_model_config''' , type=lowerCAmelCase__ , default='''roberta-base''' , help='''The model config to use. Note that we don\'t copy the model\'s weights, only the config!''' , ) parser.add_argument( '''--tokenizer''' , type=lowerCAmelCase__ , default='''unigram-tokenizer-wikitext''' , help='''The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model\'s vocab size.''' , ) parser.add_argument( '''--per_replica_batch_size''' , type=lowerCAmelCase__ , default=8 , help='''Batch size per TPU core.''' , ) parser.add_argument( '''--no_tpu''' , action='''store_true''' , help='''If set, run on CPU and don\'t try to initialize a TPU. Useful for debugging on non-TPU instances.''' , ) parser.add_argument( '''--tpu_name''' , type=lowerCAmelCase__ , help='''Name of TPU resource to initialize. Should be blank on Colab, and \'local\' on TPU VMs.''' , default='''local''' , ) parser.add_argument( '''--tpu_zone''' , type=lowerCAmelCase__ , help='''Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.''' , ) parser.add_argument( '''--gcp_project''' , type=lowerCAmelCase__ , help='''Google cloud project name. Only used for non-Colab TPU nodes.''' ) parser.add_argument( '''--bfloat16''' , action='''store_true''' , help='''Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.''' , ) parser.add_argument( '''--train_dataset''' , type=lowerCAmelCase__ , help='''Path to training dataset to load. If the path begins with `gs://`''' ''' then the dataset will be loaded from a Google Cloud Storage bucket.''' , ) parser.add_argument( '''--shuffle_buffer_size''' , type=lowerCAmelCase__ , default=2**18 , help='''Size of the shuffle buffer (in samples)''' , ) parser.add_argument( '''--eval_dataset''' , type=lowerCAmelCase__ , help='''Path to evaluation dataset to load. If the path begins with `gs://`''' ''' then the dataset will be loaded from a Google Cloud Storage bucket.''' , ) parser.add_argument( '''--num_epochs''' , type=lowerCAmelCase__ , default=1 , help='''Number of epochs to train for.''' , ) parser.add_argument( '''--learning_rate''' , type=lowerCAmelCase__ , default=1e-4 , help='''Learning rate to use for training.''' , ) parser.add_argument( '''--weight_decay_rate''' , type=lowerCAmelCase__ , default=1e-3 , help='''Weight decay rate to use for training.''' , ) parser.add_argument( '''--max_length''' , type=lowerCAmelCase__ , default=512 , help='''Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py''' , ) parser.add_argument( '''--mlm_probability''' , type=lowerCAmelCase__ , default=0.15 , help='''Fraction of tokens to mask during training.''' , ) parser.add_argument('''--output_dir''' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to save model checkpoints to.''' ) parser.add_argument('''--hub_model_id''' , type=lowerCAmelCase__ , help='''Model ID to upload to on the Hugging Face Hub.''' ) __a = parser.parse_args() return args def lowercase ( lowerCAmelCase__ : Optional[int] ) -> int: try: if args.tpu_name: __a = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: __a = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( '''Couldn\'t connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or ''' '''--gcp_project. When running on a TPU VM, use --tpu_name local.''' ) tf.config.experimental_connect_to_cluster(lowerCAmelCase__ ) tf.tpu.experimental.initialize_tpu_system(lowerCAmelCase__ ) return tpu def lowercase ( lowerCAmelCase__ : Dict ) -> Dict: __a = 0 for file in file_list: __a = file.split('''/''' )[-1] __a = re.search(r'''-\d+-(\d+)\.tfrecord''' , lowerCAmelCase__ ).group(1 ) __a = int(lowerCAmelCase__ ) num_samples += sample_count return num_samples def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int]=None ) -> Tuple: __a = count_samples(lowerCAmelCase__ ) __a = tf.data.Dataset.from_tensor_slices(lowerCAmelCase__ ) if shuffle: __a = dataset.shuffle(len(lowerCAmelCase__ ) ) __a = tf.data.TFRecordDataset(lowerCAmelCase__ , num_parallel_reads=lowerCAmelCase__ ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here __a = dataset.apply(tf.data.experimental.assert_cardinality(lowerCAmelCase__ ) ) __a = dataset.map(lowerCAmelCase__ , num_parallel_calls=lowerCAmelCase__ ) if shuffle: assert shuffle_buffer_size is not None __a = dataset.shuffle(args.shuffle_buffer_size ) __a = dataset.batch(lowerCAmelCase__ , drop_remainder=lowerCAmelCase__ ) __a = dataset.map(lowerCAmelCase__ , num_parallel_calls=lowerCAmelCase__ ) __a = dataset.prefetch(lowerCAmelCase__ ) return dataset def lowercase ( lowerCAmelCase__ : str ) -> List[str]: if not args.no_tpu: __a = initialize_tpu(lowerCAmelCase__ ) __a = tf.distribute.TPUStrategy(lowerCAmelCase__ ) else: __a = tf.distribute.OneDeviceStrategy(device='''/gpu:0''' ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy('''mixed_bfloat16''' ) __a = AutoTokenizer.from_pretrained(args.tokenizer ) __a = AutoConfig.from_pretrained(args.pretrained_model_config ) __a = tokenizer.vocab_size __a = tf.io.gfile.glob(os.path.join(args.train_dataset , '''*.tfrecord''' ) ) if not training_records: raise ValueError(f'''No .tfrecord files found in {args.train_dataset}.''' ) __a = tf.io.gfile.glob(os.path.join(args.eval_dataset , '''*.tfrecord''' ) ) if not eval_records: raise ValueError(f'''No .tfrecord files found in {args.eval_dataset}.''' ) __a = count_samples(lowerCAmelCase__ ) __a = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) __a = steps_per_epoch * args.num_epochs with strategy.scope(): __a = TFAutoModelForMaskedLM.from_config(lowerCAmelCase__ ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built __a , __a = create_optimizer( num_train_steps=lowerCAmelCase__ , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=lowerCAmelCase__ , metrics=['''accuracy'''] ) def decode_fn(lowerCAmelCase__ : Tuple ): __a = { '''input_ids''': tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), '''attention_mask''': tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(lowerCAmelCase__ , lowerCAmelCase__ ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. __a = DataCollatorForLanguageModeling( tokenizer=lowerCAmelCase__ , mlm_probability=args.mlm_probability , mlm=lowerCAmelCase__ , return_tensors='''tf''' ) def mask_with_collator(lowerCAmelCase__ : List[Any] ): # TF really needs an isin() function __a = ( ~tf.cast(batch['''attention_mask'''] , tf.bool ) | (batch['''input_ids'''] == tokenizer.cls_token_id) | (batch['''input_ids'''] == tokenizer.sep_token_id) ) __a , __a = data_collator.tf_mask_tokens( batch['''input_ids'''] , vocab_size=len(lowerCAmelCase__ ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=lowerCAmelCase__ , ) return batch __a = args.per_replica_batch_size * strategy.num_replicas_in_sync __a = prepare_dataset( lowerCAmelCase__ , decode_fn=lowerCAmelCase__ , mask_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ , shuffle=lowerCAmelCase__ , shuffle_buffer_size=args.shuffle_buffer_size , ) __a = prepare_dataset( lowerCAmelCase__ , decode_fn=lowerCAmelCase__ , mask_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ , shuffle=lowerCAmelCase__ , ) __a = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=lowerCAmelCase__ ) ) model.fit( lowerCAmelCase__ , validation_data=lowerCAmelCase__ , epochs=args.num_epochs , callbacks=lowerCAmelCase__ , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": lowercase_ = parse_args() main(args)
45
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
1
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a ): super().__init__() __a = nn.ModuleList(_a ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a = None , _a = None , _a = None , _a = None , _a = False , _a = True , ): for i, (image, scale, controlnet) in enumerate(zip(_a , _a , self.nets ) ): __a , __a = controlnet( _a , _a , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) # merge samples if i == 0: __a , __a = down_samples, mid_sample else: __a = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(_a , _a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def __UpperCAmelCase ( self , _a , _a = True , _a = None , _a = False , _a = None , ): __a = 0 __a = save_directory for controlnet in self.nets: controlnet.save_pretrained( _a , is_main_process=_a , save_function=_a , safe_serialization=_a , variant=_a , ) idx += 1 __a = model_path_to_save + f'''_{idx}''' @classmethod def __UpperCAmelCase ( cls , _a , **_a ): __a = 0 __a = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __a = pretrained_model_path while os.path.isdir(_a ): __a = ControlNetModel.from_pretrained(_a , **_a ) controlnets.append(_a ) idx += 1 __a = pretrained_model_path + f'''_{idx}''' logger.info(f'''{len(_a )} controlnets loaded from {pretrained_model_path}.''' ) if len(_a ) == 0: raise ValueError( f'''No ControlNets found under {os.path.dirname(_a )}. Expected at least {pretrained_model_path + '_0'}.''' ) return cls(_a )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ) -> Optional[Any]: return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str]=0 ) -> str: return sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : x[column] ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str]=float('''inf''' ) ) -> Any: for i in range(points_counts - 1 ): for j in range(i + 1 , lowerCAmelCase__ ): __a = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __a = current_dis return min_dis def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=float('''inf''' ) ) -> Union[str, Any]: for i in range(min(6 , points_counts - 1 ) , lowerCAmelCase__ ): for j in range(max(0 , i - 6 ) , lowerCAmelCase__ ): __a = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __a = current_dis return min_dis def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[str] ) -> List[str]: # base case if points_counts <= 3: return dis_between_closest_pair(lowerCAmelCase__ , lowerCAmelCase__ ) # recursion __a = points_counts // 2 __a = closest_pair_of_points_sqr( lowerCAmelCase__ , points_sorted_on_y[:mid] , lowerCAmelCase__ ) __a = closest_pair_of_points_sqr( lowerCAmelCase__ , points_sorted_on_y[mid:] , points_counts - mid ) __a = min(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(lowerCAmelCase__ ) __a = dis_between_closest_in_strip( lowerCAmelCase__ , len(lowerCAmelCase__ ) , lowerCAmelCase__ ) return min(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ) -> List[Any]: __a = column_based_sort(lowerCAmelCase__ , column=0 ) __a = column_based_sort(lowerCAmelCase__ , column=1 ) return ( closest_pair_of_points_sqr( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) ) ** 0.5 if __name__ == "__main__": lowercase_ = [(2, 3), (1_2, 3_0), (4_0, 5_0), (5, 1), (1_2, 1_0), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) lowercase_ = logging.getLogger() lowercase_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): os.makedirs(_a , exist_ok=_a ) __a = {'''source''': '''What is love ?''', '''target''': '''life'''} __a = {'''train''': 12, '''val''': 2, '''test''': 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: __a = '''\n'''.join([contents[field]] * n_lines[split] ) with open(os.path.join(_a , f'''{split}.{field}''' ) , '''w''' ) as f: f.write(_a ) def __UpperCAmelCase ( self , _a , _a = "pytorch" ): __a = self.get_auto_remove_tmp_dir() __a = os.path.join(_a , '''output''' ) __a = os.path.join(_a , '''data''' ) self._create_dummy_data(data_dir=_a ) __a = f''' --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''' ) if is_apex_available(): testargs.append('''--fp16''' ) else: testargs.append('''--gpus=0''' ) testargs.append('''--distributed_backend=ddp_cpu''' ) testargs.append('''--num_processes=2''' ) __a = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(_a , env=self.get_env() ) __a = os.path.join(_a , '''metrics.json''' ) with open(_a ) as f: __a = json.load(_a ) return result @require_torch_gpu def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_gpu @require_ray def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu @require_ray def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
45
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
1
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_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 ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=2 , _a=24 , _a=16 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , _a=2 , _a=2 , ): __a = parent __a = batch_size __a = patch_size __a = max_length __a = num_mel_bins __a = is_training __a = use_labels __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = type_sequence_label_size __a = initializer_range __a = scope __a = frequency_stride __a = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __a = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 __a = (self.max_length - self.patch_size) // self.time_stride + 1 __a = frequency_out_dimension * time_out_dimension __a = num_patches + 2 def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, input_values, labels def __UpperCAmelCase ( self ): return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = ASTModel(config=_a ) model.to(_a ) model.eval() __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_values''': input_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def __UpperCAmelCase ( self ): __a = ASTModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def __UpperCAmelCase ( self ): __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 = ['''input_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ASTModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> int: __a = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) __a , __a = torchaudio.load(lowerCAmelCase__ ) return audio, sampling_rate @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def __UpperCAmelCase ( self ): __a = self.default_feature_extractor __a = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(_a ) __a = self.default_feature_extractor __a , __a = prepare_audio() __a = audio.squeeze().numpy() __a = feature_extractor(_a , sampling_rate=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) )
45
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
1
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : torch.FloatTensor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' @register_to_config def __init__( self , _a = 65_536 , _a = None , _a = 2 , _a = 2 , _a = 0 , _a = "fourier" , _a = True , _a = False , _a = 0.0 , _a = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , _a = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , _a = "UNetMidBlock1D" , _a = None , _a = (32, 32, 64) , _a = None , _a = 8 , _a = 1 , _a = False , ): super().__init__() __a = sample_size # time if time_embedding_type == "fourier": __a = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=_a , log=_a , flip_sin_to_cos=_a ) __a = 2 * block_out_channels[0] elif time_embedding_type == "positional": __a = Timesteps( block_out_channels[0] , flip_sin_to_cos=_a , downscale_freq_shift=_a ) __a = block_out_channels[0] if use_timestep_embedding: __a = block_out_channels[0] * 4 __a = TimestepEmbedding( in_channels=_a , time_embed_dim=_a , act_fn=_a , out_dim=block_out_channels[0] , ) __a = nn.ModuleList([] ) __a = None __a = nn.ModuleList([] ) __a = None # down __a = in_channels for i, down_block_type in enumerate(_a ): __a = output_channel __a = block_out_channels[i] if i == 0: input_channel += extra_in_channels __a = i == len(_a ) - 1 __a = get_down_block( _a , num_layers=_a , in_channels=_a , out_channels=_a , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(_a ) # mid __a = get_mid_block( _a , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=_a , add_downsample=_a , ) # up __a = list(reversed(_a ) ) __a = reversed_block_out_channels[0] if out_block_type is None: __a = out_channels else: __a = block_out_channels[0] for i, up_block_type in enumerate(_a ): __a = output_channel __a = ( reversed_block_out_channels[i + 1] if i < len(_a ) - 1 else final_upsample_channels ) __a = i == len(_a ) - 1 __a = get_up_block( _a , num_layers=_a , in_channels=_a , out_channels=_a , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(_a ) __a = output_channel # out __a = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) __a = get_out_block( out_block_type=_a , num_groups_out=_a , embed_dim=block_out_channels[0] , out_channels=_a , act_fn=_a , fc_dim=block_out_channels[-1] // 4 , ) def __UpperCAmelCase ( self , _a , _a , _a = True , ): __a = timestep if not torch.is_tensor(_a ): __a = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0: __a = timesteps[None].to(sample.device ) __a = self.time_proj(_a ) if self.config.use_timestep_embedding: __a = self.time_mlp(_a ) else: __a = timestep_embed[..., None] __a = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) __a = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down __a = () for downsample_block in self.down_blocks: __a , __a = downsample_block(hidden_states=_a , temb=_a ) down_block_res_samples += res_samples # 3. mid if self.mid_block: __a = self.mid_block(_a , _a ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): __a = down_block_res_samples[-1:] __a = down_block_res_samples[:-1] __a = upsample_block(_a , res_hidden_states_tuple=_a , temb=_a ) # 5. post-process if self.out_block: __a = self.out_block(_a , _a ) if not return_dict: return (sample,) return UNetaDOutput(sample=_a )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "vocab_file": "vocab.json", "merges_file": "merges.txt", } lowercase_ = { "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"}, "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"}, } lowercase_ = { "ctrl": 2_5_6, } lowercase_ = { "Pregnancy": 1_6_8_6_2_9, "Christianity": 7_6_7_5, "Explain": 1_0_6_4_2_3, "Fitness": 6_3_4_4_0, "Saving": 6_3_1_6_3, "Ask": 2_7_1_7_1, "Ass": 9_5_9_8_5, "Joke": 1_6_3_5_0_9, "Questions": 4_5_6_2_2, "Thoughts": 4_9_6_0_5, "Retail": 5_2_3_4_2, "Feminism": 1_6_4_3_3_8, "Writing": 1_1_9_9_2, "Atheism": 1_9_2_2_6_3, "Netflix": 4_8_6_1_6, "Computing": 3_9_6_3_9, "Opinion": 4_3_2_1_3, "Alone": 4_4_9_6_7, "Funny": 5_8_9_1_7, "Gaming": 4_0_3_5_8, "Human": 4_0_8_8, "India": 1_3_3_1, "Joker": 7_7_1_3_8, "Diet": 3_6_2_0_6, "Legal": 1_1_8_5_9, "Norman": 4_9_3_9, "Tip": 7_2_6_8_9, "Weight": 5_2_3_4_3, "Movies": 4_6_2_7_3, "Running": 2_3_4_2_5, "Science": 2_0_9_0, "Horror": 3_7_7_9_3, "Confession": 6_0_5_7_2, "Finance": 1_2_2_5_0, "Politics": 1_6_3_6_0, "Scary": 1_9_1_9_8_5, "Support": 1_2_6_5_4, "Technologies": 3_2_5_1_6, "Teenage": 6_6_1_6_0, "Event": 3_2_7_6_9, "Learned": 6_7_4_6_0, "Notion": 1_8_2_7_7_0, "Wikipedia": 3_7_5_8_3, "Books": 6_6_6_5, "Extract": 7_6_0_5_0, "Confessions": 1_0_2_7_0_1, "Conspiracy": 7_5_9_3_2, "Links": 6_3_6_7_4, "Narcissus": 1_5_0_4_2_5, "Relationship": 5_4_7_6_6, "Relationships": 1_3_4_7_9_6, "Reviews": 4_1_6_7_1, "News": 4_2_5_6, "Translation": 2_6_8_2_0, "multilingual": 1_2_8_4_0_6, } def lowercase ( lowerCAmelCase__ : List[str] ) -> str: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char __a = set(lowerCAmelCase__ ) return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : int = CONTROL_CODES def __init__( self , _a , _a , _a="<unk>" , **_a ): super().__init__(unk_token=_a , **_a ) with open(_a , encoding='''utf-8''' ) as vocab_handle: __a = json.load(_a ) __a = {v: k for k, v in self.encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in merges] __a = dict(zip(_a , range(len(_a ) ) ) ) __a = {} @property def __UpperCAmelCase ( self ): return len(self.encoder ) def __UpperCAmelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _a ): if token in self.cache: return self.cache[token] __a = tuple(_a ) __a = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) __a = get_pairs(_a ) if not pairs: return token while True: __a = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(_a ): try: __a = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(_a ) __a = new_word if len(_a ) == 1: break else: __a = get_pairs(_a ) __a = '''@@ '''.join(_a ) __a = word[:-4] __a = word return word def __UpperCAmelCase ( self , _a ): __a = [] __a = re.findall(R'''\S+\n?''' , _a ) for token in words: split_tokens.extend(list(self.bpe(_a ).split(''' ''' ) ) ) return split_tokens def __UpperCAmelCase ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self , _a ): return self.decoder.get(_a , self.unk_token ) def __UpperCAmelCase ( self , _a ): __a = ''' '''.join(_a ).replace('''@@ ''' , '''''' ).strip() return out_string def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) __a = 0 with open(_a , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __a = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
1
"""simple docstring""" from __future__ import annotations import requests lowercase_ = set( "approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports".split() ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : int = 1 , lowerCAmelCase__ : str = "new" , lowerCAmelCase__ : list | None = None ) -> dict: __a = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(lowerCAmelCase__ ) - valid_terms ) ): __a = f'''Invalid search term: {invalid_search_terms}''' raise ValueError(lowerCAmelCase__ ) __a = requests.get( f'''https://reddit.com/r/{subreddit}/{age}.json?limit={limit}''' , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError __a = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(lowerCAmelCase__ )} __a = {} for id_ in range(lowerCAmelCase__ ): __a = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
45
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig lowercase_ = { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/config.json", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/config.json", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/config.json", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/config.json", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/config.json", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/config.json", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = 'albert' def __init__( self , _a=30_000 , _a=128 , _a=4_096 , _a=12 , _a=1 , _a=64 , _a=16_384 , _a=1 , _a="gelu_new" , _a=0 , _a=0 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=0.1 , _a="absolute" , _a=0 , _a=2 , _a=3 , **_a , ): super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = classifier_dropout_prob __a = position_embedding_type class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCAmelCase ( self ): if self.task == "multiple-choice": __a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
45
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
45
1
"""simple docstring""" import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) __a = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) __a = '''The dog is cute and lives in the garden house''' __a = jnp.array([tokenizer.encode(_a )] ) __a = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim __a = jnp.array( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) __a = model(_a )['''last_hidden_state'''] self.assertEqual(output.shape , _a ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , _a , atol=1E-3 ) )
45
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" 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 lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "spm_char.model"} lowercase_ = { "vocab_file": { "microsoft/speecht5_asr": "https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model", "microsoft/speecht5_tts": "https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model", "microsoft/speecht5_vc": "https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model", } } lowercase_ = { "microsoft/speecht5_asr": 1_0_2_4, "microsoft/speecht5_tts": 1_0_2_4, "microsoft/speecht5_vc": 1_0_2_4, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : int = VOCAB_FILES_NAMES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Tuple = ['input_ids', 'attention_mask'] def __init__( self , _a , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<pad>" , _a = None , **_a , ): __a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , pad_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) __a = vocab_file __a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def __UpperCAmelCase ( self ): return self.sp_model.get_piece_size() def __UpperCAmelCase ( self ): __a = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): __a = self.__dict__.copy() __a = None return state def __setstate__( self , _a ): __a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __a = {} __a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __UpperCAmelCase ( self , _a ): return self.sp_model.encode(_a , out_type=_a ) def __UpperCAmelCase ( self , _a ): return self.sp_model.piece_to_id(_a ) def __UpperCAmelCase ( self , _a ): __a = self.sp_model.IdToPiece(_a ) return token def __UpperCAmelCase ( self , _a ): __a = [] __a = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_a ) + token __a = [] else: current_sub_tokens.append(_a ) out_string += self.sp_model.decode(_a ) return out_string.strip() def __UpperCAmelCase ( self , _a , _a=None ): if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __UpperCAmelCase ( self , _a , _a = None , _a = 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 ) __a = [1] if token_ids_a is None: return ([0] * len(_a )) + suffix_ones return ([0] * len(_a )) + ([0] * len(_a )) + suffix_ones def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = 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: __a = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
1
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[str]] , lowerCAmelCase__ : int , ) -> None: __a = len(lowerCAmelCase__ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(lowerCAmelCase__ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , lowerCAmelCase__ , lowerCAmelCase__ , ) def lowercase ( lowerCAmelCase__ : int ) -> None: __a = [] depth_first_search([] , [] , [] , lowerCAmelCase__ , lowerCAmelCase__ ) # Print all the boards for board in boards: for column in board: print(lowerCAmelCase__ ) print('''''' ) print(len(lowerCAmelCase__ ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
45
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
1
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( lowerCAmelCase__ : float = 0.1 ) -> int: __a = 3 __a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowerCAmelCase__ ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
1
"""simple docstring""" from math import factorial, pi def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : int = 30 ) -> float: if not isinstance(lowerCAmelCase__ , (int, float) ): raise ValueError('''maclaurin_sin() requires either an int or float for theta''' ) if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or accuracy <= 0: raise ValueError('''maclaurin_sin() requires a positive int for accuracy''' ) __a = float(lowerCAmelCase__ ) __a = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(lowerCAmelCase__ ) ) def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : int = 30 ) -> float: if not isinstance(lowerCAmelCase__ , (int, float) ): raise ValueError('''maclaurin_cos() requires either an int or float for theta''' ) if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or accuracy <= 0: raise ValueError('''maclaurin_cos() requires a positive int for accuracy''' ) __a = float(lowerCAmelCase__ ) __a = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(lowerCAmelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
45
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = self._index.query(_a ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(_a , _a ) if len(_a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_a ) break else: self._duplicate_clusters[close_duplicates[0]].add(_a ) def __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase__ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__ ) ) , max_queue_size=100 ) ): di.add(lowerCAmelCase__ , lowerCAmelCase__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCAmelCase__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCAmelCase__ , lowerCAmelCase__ , ) , total=len(lowerCAmelCase__ ) , ): extremes_list.append(lowerCAmelCase__ ) return extremes_list def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = dataset.filter(lambda lowerCAmelCase__ , lowerCAmelCase__ : idx not in remove_indices , with_indices=lowerCAmelCase__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = extreme_dict[element['''base_index''']]['''copies'''] print(f'''Original dataset size: {len(lowerCAmelCase__ )}''' ) print(f'''Number of duplicate clusters: {len(lowerCAmelCase__ )}''' ) print(f'''Files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Unique files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Filtered dataset size: {len(lowerCAmelCase__ )}''' ) return ds_filter, duplicate_clusters
45
1
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = (DDPMParallelScheduler,) def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_000, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**_a ) return config def __UpperCAmelCase ( self ): for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCAmelCase ( self ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def __UpperCAmelCase ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def __UpperCAmelCase ( self ): for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def __UpperCAmelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __UpperCAmelCase ( self ): self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def __UpperCAmelCase ( self ): for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_0979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = len(_a ) __a = self.dummy_model() __a = self.dummy_sample_deter __a = self.dummy_sample_deter + 0.1 __a = self.dummy_sample_deter - 0.1 __a = samplea.shape[0] __a = torch.stack([samplea, samplea, samplea] , dim=0 ) __a = torch.arange(_a )[0:3, None].repeat(1 , _a ) __a = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __a = scheduler.batch_step_no_noise(_a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 1153.1833 ) < 1E-2 assert abs(result_mean.item() - 0.5005 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = len(_a ) __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual __a = model(_a , _a ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_a , _a , _a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9606 ) < 1E-2 assert abs(result_mean.item() - 0.3372 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(prediction_type='''v_prediction''' ) __a = scheduler_class(**_a ) __a = len(_a ) __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual __a = model(_a , _a ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_a , _a , _a , generator=_a ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_a ) ) __a = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0296 ) < 1E-2 assert abs(result_mean.item() - 0.2631 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) __a = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: __a = -1 else: __a = timesteps[i + 1] __a = scheduler.previous_timestep(_a ) __a = prev_t.item() self.assertEqual(_a , _a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = [100, 87, 50, 1, 0] __a = len(_a ) with self.assertRaises(_a , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_a ) __a = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=_a )
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline lowercase_ = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' __UpperCAmelCase : Optional[datasets.Features] = None __UpperCAmelCase : str = "utf-8" __UpperCAmelCase : Optional[str] = None __UpperCAmelCase : Optional[str] = None __UpperCAmelCase : bool = True # deprecated __UpperCAmelCase : Optional[int] = None # deprecated __UpperCAmelCase : int = 1_0 << 2_0 # 10MB __UpperCAmelCase : Optional[bool] = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = JsonConfig def __UpperCAmelCase ( self ): if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' ) __a = self.config.block_size if self.config.use_threads is not True: logger.warning( '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''' ) if self.config.newlines_in_values is not None: raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''' ) return datasets.DatasetInfo(features=self.config.features ) def __UpperCAmelCase ( self , _a ): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) __a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_a , (str, list, tuple) ): __a = data_files if isinstance(_a , _a ): __a = [files] __a = [dl_manager.iter_files(_a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] __a = [] for split_name, files in data_files.items(): if isinstance(_a , _a ): __a = [files] __a = [dl_manager.iter_files(_a ) for file in files] splits.append(datasets.SplitGenerator(name=_a , gen_kwargs={'''files''': files} ) ) return splits def __UpperCAmelCase ( self , _a ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): __a = self.config.features.arrow_schema.field(_a ).type __a = pa_table.append_column(_a , pa.array([None] * len(_a ) , type=_a ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example __a = table_cast(_a , self.config.features.arrow_schema ) return pa_table def __UpperCAmelCase ( self , _a ): for file_idx, file in enumerate(itertools.chain.from_iterable(_a ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(_a , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: __a = json.load(_a ) # We keep only the field we are interested in __a = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(_a , (list, tuple) ): __a = set().union(*[row.keys() for row in dataset] ) __a = {col: [row.get(_a ) for row in dataset] for col in keys} else: __a = dataset __a = pa.Table.from_pydict(_a ) yield file_idx, self._cast_table(_a ) # If the file has one json object per line else: with open(_a , '''rb''' ) as f: __a = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small __a = max(self.config.chunksize // 32 , 16 << 10 ) __a = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: __a = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(_a ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": __a = batch.decode(self.config.encoding , errors=_a ).encode('''utf-8''' ) try: while True: try: __a = paj.read_json( io.BytesIO(_a ) , read_options=paj.ReadOptions(block_size=_a ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(_a , pa.ArrowInvalid ) and "straddling" not in str(_a ) or block_size > len(_a ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( f'''Batch of {len(_a )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.''' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( _a , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: __a = json.load(_a ) except json.JSONDecodeError: logger.error(f'''Failed to read file \'{file}\' with error {type(_a )}: {e}''' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(_a , _a ): # list is the only sequence type supported in JSON try: __a = set().union(*[row.keys() for row in dataset] ) __a = {col: [row.get(_a ) for row in dataset] for col in keys} __a = pa.Table.from_pydict(_a ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_a )}: {e}''' ) raise ValueError(f'''Not able to read records in the JSON file at {file}.''' ) from None yield file_idx, self._cast_table(_a ) break else: logger.error(f'''Failed to read file \'{file}\' with error {type(_a )}: {e}''' ) raise ValueError( f'''Not able to read records in the JSON file at {file}. ''' f'''You should probably indicate the field of the JSON file containing your records. ''' f'''This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ''' f'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ''' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_a ) batch_idx += 1
45
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
1
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , _a , _a=7 , _a=3 , _a=30 , _a=400 , _a=True , _a=None , _a=True , _a=1 / 255 , _a=True , _a=[0.5, 0.5, 0.5] , _a=[0.5, 0.5, 0.5] , _a=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1_333} __a = parent __a = batch_size __a = num_channels __a = min_resolution __a = max_resolution __a = do_resize __a = size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean __a = image_std __a = do_pad def __UpperCAmelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __UpperCAmelCase ( self , _a , _a=False ): if not batched: __a = image_inputs[0] if isinstance(_a , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size['''shortest_edge'''] * h / w ) __a = self.size['''shortest_edge'''] elif w > h: __a = self.size['''shortest_edge'''] __a = int(self.size['''shortest_edge'''] * w / h ) else: __a = self.size['''shortest_edge'''] __a = self.size['''shortest_edge'''] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(_a , key=lambda _a : item[0] )[0] __a = max(_a , key=lambda _a : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = DetrImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self ): __a = DetrImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): __a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , '''image_mean''' ) ) self.assertTrue(hasattr(_a , '''image_std''' ) ) self.assertTrue(hasattr(_a , '''do_normalize''' ) ) self.assertTrue(hasattr(_a , '''do_rescale''' ) ) self.assertTrue(hasattr(_a , '''rescale_factor''' ) ) self.assertTrue(hasattr(_a , '''do_resize''' ) ) self.assertTrue(hasattr(_a , '''size''' ) ) self.assertTrue(hasattr(_a , '''do_pad''' ) ) def __UpperCAmelCase ( self ): __a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1_333} ) self.assertEqual(image_processor.do_pad , _a ) __a = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_a ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , _a ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(_a , batched=_a ) __a = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(_a , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(_a , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __UpperCAmelCase ( self ): # prepare image and target __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __a = json.loads(f.read() ) __a = {'''image_id''': 39_769, '''annotations''': target} # encode them __a = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50''' ) __a = image_processing(images=_a , annotations=_a , return_tensors='''pt''' ) # verify pixel values __a = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , _a ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _a , atol=1E-4 ) ) # verify area __a = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _a ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _a ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _a , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _a ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _a ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _a ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _a ) ) # verify size __a = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _a ) ) @slow def __UpperCAmelCase ( self ): # prepare image, target and masks_path __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __a = json.loads(f.read() ) __a = {'''file_name''': '''000000039769.png''', '''image_id''': 39_769, '''segments_info''': target} __a = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __a = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic''' ) __a = image_processing(images=_a , annotations=_a , masks_path=_a , return_tensors='''pt''' ) # verify pixel values __a = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , _a ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _a , atol=1E-4 ) ) # verify area __a = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _a ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _a ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _a , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _a ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _a ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _a ) ) # verify masks __a = 822_873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _a ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _a ) ) # verify size __a = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _a ) )
45
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
1
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = True __a = 99 __a = 384 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = 128 __a = 2 __a = 9 __a = 1 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=_a , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = TFConvBertModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = TFConvBertForMaskedLM(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFConvBertForSequenceClassification(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = TFConvBertForMultipleChoice(config=_a ) __a = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) __a = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) __a = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) __a = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFConvBertForTokenClassification(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = TFConvBertForQuestionAnswering(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __a = model(_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __UpperCAmelCase : str = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : str = False __UpperCAmelCase : str = False __UpperCAmelCase : Optional[Any] = False def __UpperCAmelCase ( self ): __a = TFConvBertModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True __a = True if hasattr(_a , '''use_cache''' ): __a = True __a = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) __a = getattr(self.model_tester , '''key_length''' , _a ) for model_class in self.all_model_classes: __a = self._prepare_for_class(_a , _a ) __a = model_class(_a ) __a = len(model(_a ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a , saved_model=_a ) __a = os.path.join(_a , '''saved_model''' , '''1''' ) __a = tf.keras.models.load_model(_a ) __a = model(_a ) if self.is_encoder_decoder: __a = outputs['''encoder_hidden_states'''] __a = outputs['''encoder_attentions'''] else: __a = outputs['''hidden_states'''] __a = outputs['''attentions'''] self.assertEqual(len(_a ) , _a ) __a = getattr( self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_a ) , _a ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __UpperCAmelCase ( self ): __a = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True __a = getattr(self.model_tester , '''decoder_seq_length''' , self.model_tester.seq_length ) __a = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) __a = getattr(self.model_tester , '''key_length''' , _a ) __a = getattr(self.model_tester , '''key_length''' , _a ) def check_decoder_attentions_output(_a ): __a = len(_a ) self.assertEqual(out_len % 2 , 0 ) __a = outputs.decoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(_a ): __a = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: __a = True __a = False __a = model_class(_a ) __a = model(self._prepare_for_class(_a , _a ) ) __a = len(_a ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) if self.is_encoder_decoder: __a = model_class(_a ) __a = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_decoder_attentions_output(_a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __a = True __a = model_class(_a ) __a = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) # Check attention is always last and order is fine __a = True __a = True __a = model_class(_a ) __a = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_a ) ) self.assertEqual(model.config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 768] self.assertEqual(output.shape , _a ) __a = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1E-4 )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import unittest from knapsack import greedy_knapsack as kp class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = [10, 20, 30, 40, 50, 60] __a = [2, 4, 6, 8, 10, 12] __a = 100 self.assertEqual(kp.calc_profit(_a , _a , _a ) , 210 ) def __UpperCAmelCase ( self ): self.assertRaisesRegex(_a , '''max_weight must greater than zero.''' ) def __UpperCAmelCase ( self ): self.assertRaisesRegex(_a , '''Weight can not be negative.''' ) def __UpperCAmelCase ( self ): self.assertRaisesRegex(_a , '''Profit can not be negative.''' ) def __UpperCAmelCase ( self ): self.assertRaisesRegex(_a , '''max_weight must greater than zero.''' ) def __UpperCAmelCase ( self ): self.assertRaisesRegex( _a , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
45
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : int = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : int = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : int = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] ) class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['sentencepiece'] def __init__( self , *_a , **_a ): requires_backends(self , ['''sentencepiece'''] )
45
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
1
"""simple docstring""" from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def __UpperCAmelCase ( self ): __a = {'''col_1''': [3, 2, 1, 0], '''col_2''': ['''a''', '''b''', '''c''', '''d''']} return Dataset.from_dict(_a ) def __UpperCAmelCase ( self ): __a = self._create_example_records() __a = Dataset.from_list(_a ) self.assertListEqual(dset.column_names , ['''col_1''', '''col_2'''] ) for i, r in enumerate(_a ): self.assertDictEqual(_a , example_records[i] ) def __UpperCAmelCase ( self ): __a = self._create_example_records() __a = Dataset.from_list(_a ) __a = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def __UpperCAmelCase ( self ): # checks what happens with missing columns __a = [{'''col_1''': 1}, {'''col_2''': '''x'''}] __a = Dataset.from_list(_a ) self.assertDictEqual(dset[0] , {'''col_1''': 1} ) self.assertDictEqual(dset[1] , {'''col_1''': None} ) # NB: first record is used for columns def __UpperCAmelCase ( self ): # checks if the type can be inferred from the second record __a = [{'''col_1''': []}, {'''col_1''': [1, 2]}] __a = Dataset.from_list(_a ) self.assertEqual(dset.info.features['''col_1'''] , Sequence(Value('''int64''' ) ) ) def __UpperCAmelCase ( self ): __a = Dataset.from_list([] ) self.assertEqual(len(_a ) , 0 ) self.assertListEqual(dset.column_names , [] )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json", "microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : int = 'markuplm' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=0 , _a=0 , _a=2 , _a=256 , _a=1_024 , _a=216 , _a=1_001 , _a=32 , _a=50 , _a="absolute" , _a=True , _a=None , **_a , ): super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a , ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = use_cache __a = classifier_dropout # additional properties __a = max_depth __a = max_xpath_tag_unit_embeddings __a = max_xpath_subs_unit_embeddings __a = tag_pad_id __a = subs_pad_id __a = xpath_unit_hidden_size
45
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
1
"""simple docstring""" from copy import deepcopy class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a = None , _a = None ): if arr is None and size is not None: __a = size __a = [0] * size elif arr is not None: self.init(_a ) else: raise ValueError('''Either arr or size must be specified''' ) def __UpperCAmelCase ( self , _a ): __a = len(_a ) __a = deepcopy(_a ) for i in range(1 , self.size ): __a = self.next_(_a ) if j < self.size: self.tree[j] += self.tree[i] def __UpperCAmelCase ( self ): __a = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): __a = self.next_(_a ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def __UpperCAmelCase ( _a ): return index + (index & (-index)) @staticmethod def __UpperCAmelCase ( _a ): return index - (index & (-index)) def __UpperCAmelCase ( self , _a , _a ): if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value __a = self.next_(_a ) def __UpperCAmelCase ( self , _a , _a ): self.add(_a , value - self.get(_a ) ) def __UpperCAmelCase ( self , _a ): if right == 0: return 0 __a = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] __a = self.prev(_a ) return result def __UpperCAmelCase ( self , _a , _a ): return self.prefix(_a ) - self.prefix(_a ) def __UpperCAmelCase ( self , _a ): return self.query(_a , index + 1 ) def __UpperCAmelCase ( self , _a ): value -= self.tree[0] if value < 0: return -1 __a = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 __a = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list[int]: __a = [0 for i in range(len(lowerCAmelCase__ ) )] # initialize interval's left pointer and right pointer __a , __a = 0, 0 for i in range(1 , len(lowerCAmelCase__ ) ): # case when current index is inside the interval if i <= right_pointer: __a = min(right_pointer - i + 1 , z_result[i - left_pointer] ) __a = min_edge while go_next(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: __a , __a = i, i + z_result[i] - 1 return z_result def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : str ) -> bool: return i + z_result[i] < len(lowerCAmelCase__ ) and s[z_result[i]] == s[i + z_result[i]] def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> int: __a = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string __a = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(lowerCAmelCase__ ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , _a , _a=7 , _a=3 , _a=30 , _a=400 , _a=True , _a=None , _a=True , _a=[0.5, 0.5, 0.5] , _a=[0.5, 0.5, 0.5] , _a=True , _a=1 / 255 , _a=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1_333} __a = parent __a = batch_size __a = num_channels __a = min_resolution __a = max_resolution __a = do_resize __a = size __a = do_normalize __a = image_mean __a = image_std __a = do_rescale __a = rescale_factor __a = do_pad def __UpperCAmelCase ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __UpperCAmelCase ( self , _a , _a=False ): if not batched: __a = image_inputs[0] if isinstance(_a , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size['''shortest_edge'''] * h / w ) __a = self.size['''shortest_edge'''] elif w > h: __a = self.size['''shortest_edge'''] __a = int(self.size['''shortest_edge'''] * w / h ) else: __a = self.size['''shortest_edge'''] __a = self.size['''shortest_edge'''] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(_a , key=lambda _a : item[0] )[0] __a = max(_a , key=lambda _a : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = ConditionalDetrImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self ): __a = ConditionalDetrImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): __a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , '''image_mean''' ) ) self.assertTrue(hasattr(_a , '''image_std''' ) ) self.assertTrue(hasattr(_a , '''do_normalize''' ) ) self.assertTrue(hasattr(_a , '''do_resize''' ) ) self.assertTrue(hasattr(_a , '''size''' ) ) def __UpperCAmelCase ( self ): __a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1_333} ) self.assertEqual(image_processor.do_pad , _a ) __a = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_a ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , _a ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(_a , batched=_a ) __a = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(_a , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input __a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(_a , return_tensors='''pt''' ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __UpperCAmelCase ( self ): # prepare image and target __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __a = json.loads(f.read() ) __a = {'''image_id''': 39_769, '''annotations''': target} # encode them __a = ConditionalDetrImageProcessor.from_pretrained('''microsoft/conditional-detr-resnet-50''' ) __a = image_processing(images=_a , annotations=_a , return_tensors='''pt''' ) # verify pixel values __a = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , _a ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _a , atol=1E-4 ) ) # verify area __a = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _a ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _a ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _a , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _a ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _a ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _a ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _a ) ) # verify size __a = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _a ) ) @slow def __UpperCAmelCase ( self ): # prepare image, target and masks_path __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __a = json.loads(f.read() ) __a = {'''file_name''': '''000000039769.png''', '''image_id''': 39_769, '''segments_info''': target} __a = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __a = ConditionalDetrImageProcessor(format='''coco_panoptic''' ) __a = image_processing(images=_a , annotations=_a , masks_path=_a , return_tensors='''pt''' ) # verify pixel values __a = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , _a ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _a , atol=1E-4 ) ) # verify area __a = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _a ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _a ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _a , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _a ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _a ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _a ) ) # verify masks __a = 822_873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _a ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _a ) ) # verify size __a = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _a ) )
45
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
1
"""simple docstring""" from manim import * class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = Rectangle(height=0.5 , width=0.5 ) __a = Rectangle(height=0.25 , width=0.25 ) __a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a = [mem.copy() for i in range(6 )] __a = [mem.copy() for i in range(6 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = VGroup(_a , _a ).arrange(_a , buff=0 ) __a = Text('''CPU''' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_a ) __a = [mem.copy() for i in range(4 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = Text('''GPU''' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) gpu.move_to([-1, -1, 0] ) self.add(_a ) __a = [mem.copy() for i in range(6 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = Text('''Model''' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) model.move_to([3, -1.0, 0] ) self.add(_a ) __a = [] __a = [] __a = [] for i, rect in enumerate(_a ): rect.set_stroke(_a ) __a = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_a ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=_a , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=_a , buff=0.0 ) self.add(_a ) model_cpu_arr.append(_a ) self.add(*_a , *_a , *_a ) __a = [mem.copy() for i in range(6 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = Text('''Loaded Checkpoint''' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) checkpoint.move_to([3, 0.5, 0] ) self.add(_a ) __a = [] __a = [] for i, rect in enumerate(_a ): __a = fill.copy().set_fill(_a , opacity=0.7 ) target.move_to(_a ) ckpt_arr.append(_a ) __a = 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(_a ) self.add(*_a , *_a ) __a = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a = 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(_a , _a ) __a = MarkupText( f'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_a ) __a = 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] ) __a = [meta_mem.copy() for i in range(6 )] __a = [meta_mem.copy() for i in range(6 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = VGroup(_a , _a ).arrange(_a , buff=0 ) __a = Text('''Disk''' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(_a , run_time=3 ) , Write(_a , run_time=1 ) , Create(_a , run_time=1 ) ) __a = [] for i, rect in enumerate(_a ): __a = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(_a , run_time=1.5 ) ) self.play(*_a ) self.play(FadeOut(_a ) ) __a = 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(_a , run_time=3 ) ) self.play( FadeOut(_a , _a , *_a , *_a ) , ) self.wait()
45
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
1
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : int = 100 ) -> int: __a = sum(i * i for i in range(1 , n + 1 ) ) __a = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F'''{solution() = }''')
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger lowercase_ = get_logger(__name__) class __lowerCAmelCase ( enum.Enum ): '''simple docstring''' __UpperCAmelCase : Dict = 'all_checks' __UpperCAmelCase : str = 'basic_checks' __UpperCAmelCase : Tuple = 'no_checks' class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def lowercase ( lowerCAmelCase__ : Optional[dict] , lowerCAmelCase__ : dict , lowerCAmelCase__ : Union[str, Any]=None ) -> List[str]: if expected_checksums is None: logger.info('''Unable to verify checksums.''' ) return if len(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) ) if len(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) > 0: raise UnexpectedDownloadedFile(str(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) ) __a = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] __a = ''' for ''' + verification_name if verification_name is not None else '''''' if len(lowerCAmelCase__ ) > 0: raise NonMatchingChecksumError( f'''Checksums didn\'t match{for_verification_name}:\n''' f'''{bad_urls}\n''' '''Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error''' ) logger.info('''All the checksums matched successfully''' + for_verification_name ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def lowercase ( lowerCAmelCase__ : Optional[dict] , lowerCAmelCase__ : dict ) -> List[str]: if expected_splits is None: logger.info('''Unable to verify splits sizes.''' ) return if len(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) > 0: raise ExpectedMoreSplits(str(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) ) if len(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) > 0: raise UnexpectedSplits(str(set(lowerCAmelCase__ ) - set(lowerCAmelCase__ ) ) ) __a = [ {'''expected''': expected_splits[name], '''recorded''': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(lowerCAmelCase__ ) > 0: raise NonMatchingSplitsSizesError(str(lowerCAmelCase__ ) ) logger.info('''All the splits matched successfully.''' ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : bool = True ) -> dict: if record_checksum: __a = shaaaa() with open(lowerCAmelCase__ , '''rb''' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , b'''''' ): m.update(lowerCAmelCase__ ) __a = m.hexdigest() else: __a = None return {"num_bytes": os.path.getsize(lowerCAmelCase__ ), "checksum": checksum} def lowercase ( lowerCAmelCase__ : Any ) -> Tuple: if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
1
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> Any: __a = fname.split(os.path.sep )[-1] return re.search(r'''^(.*)_\d+\.jpg$''' , lowerCAmelCase__ ).groups()[0] class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a=None , _a=None ): __a = file_names __a = image_transform __a = label_to_id def __len__( self ): return len(self.file_names ) def __getitem__( self , _a ): __a = self.file_names[idx] __a = PIL.Image.open(_a ) __a = raw_image.convert('''RGB''' ) if self.image_transform is not None: __a = self.image_transform(_a ) __a = extract_label(_a ) if self.label_to_id is not None: __a = self.label_to_id[label] return {"image": image, "label": label} def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] ) -> Tuple: # Initialize accelerator if args.with_tracking: __a = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir ) else: __a = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a = config['''lr'''] __a = int(config['''num_epochs'''] ) __a = int(config['''seed'''] ) __a = int(config['''batch_size'''] ) __a = config['''image_size'''] if not isinstance(lowerCAmelCase__ , (list, tuple) ): __a = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , '''isdigit''' ): if args.checkpointing_steps == "epoch": __a = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): __a = int(args.checkpointing_steps ) else: raise ValueError( f'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''' ) else: __a = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: __a = os.path.split(lowerCAmelCase__ )[-1].split('''.''' )[0] accelerator.init_trackers(lowerCAmelCase__ , lowerCAmelCase__ ) # Grab all the image filenames __a = [os.path.join(args.data_dir , lowerCAmelCase__ ) for fname in os.listdir(args.data_dir ) if fname.endswith('''.jpg''' )] # Build the label correspondences __a = [extract_label(lowerCAmelCase__ ) for fname in file_names] __a = list(set(lowerCAmelCase__ ) ) id_to_label.sort() __a = {lbl: i for i, lbl in enumerate(lowerCAmelCase__ )} # Set the seed before splitting the data. np.random.seed(lowerCAmelCase__ ) torch.manual_seed(lowerCAmelCase__ ) torch.cuda.manual_seed_all(lowerCAmelCase__ ) # Split our filenames between train and validation __a = np.random.permutation(len(lowerCAmelCase__ ) ) __a = int(0.8 * len(lowerCAmelCase__ ) ) __a = random_perm[:cut] __a = random_perm[cut:] # For training we use a simple RandomResizedCrop __a = Compose([RandomResizedCrop(lowerCAmelCase__ , scale=(0.5, 1.0) ), ToTensor()] ) __a = PetsDataset( [file_names[i] for i in train_split] , image_transform=lowerCAmelCase__ , label_to_id=lowerCAmelCase__ ) # For evaluation, we use a deterministic Resize __a = Compose([Resize(lowerCAmelCase__ ), ToTensor()] ) __a = PetsDataset([file_names[i] for i in eval_split] , image_transform=lowerCAmelCase__ , label_to_id=lowerCAmelCase__ ) # Instantiate dataloaders. __a = DataLoader(lowerCAmelCase__ , shuffle=lowerCAmelCase__ , batch_size=lowerCAmelCase__ , num_workers=4 ) __a = DataLoader(lowerCAmelCase__ , shuffle=lowerCAmelCase__ , batch_size=lowerCAmelCase__ , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a = create_model('''resnet50d''' , pretrained=lowerCAmelCase__ , num_classes=len(lowerCAmelCase__ ) ) # 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). __a = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): __a = False for param in model.get_classifier().parameters(): __a = True # We normalize the batches of images to be a bit faster. __a = torch.tensor(model.default_cfg['''mean'''] )[None, :, None, None].to(accelerator.device ) __a = torch.tensor(model.default_cfg['''std'''] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer __a = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler __a = OneCycleLR(optimizer=lowerCAmelCase__ , max_lr=lowerCAmelCase__ , epochs=lowerCAmelCase__ , steps_per_epoch=len(lowerCAmelCase__ ) ) # 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. __a , __a , __a , __a , __a = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # We need to keep track of how many total steps we have iterated over __a = 0 # We also need to keep track of the starting epoch so files are named properly __a = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(f'''Resumed from checkpoint: {args.resume_from_checkpoint}''' ) accelerator.load_state(args.resume_from_checkpoint ) __a = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint __a = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) __a = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` __a = os.path.splitext(lowerCAmelCase__ )[0] if "epoch" in training_difference: __a = int(training_difference.replace('''epoch_''' , '''''' ) ) + 1 __a = None else: __a = int(training_difference.replace('''step_''' , '''''' ) ) __a = resume_step // len(lowerCAmelCase__ ) resume_step -= starting_epoch * len(lowerCAmelCase__ ) # Now we train the model for epoch in range(lowerCAmelCase__ , lowerCAmelCase__ ): model.train() if args.with_tracking: __a = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step __a = accelerator.skip_first_batches(lowerCAmelCase__ , lowerCAmelCase__ ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader __a = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. __a = {k: v.to(accelerator.device ) for k, v in batch.items()} __a = (batch['''image'''] - mean) / std __a = model(lowerCAmelCase__ ) __a = torch.nn.functional.cross_entropy(lowerCAmelCase__ , batch['''label'''] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(lowerCAmelCase__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''step_{overall_step}''' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: __a = os.path.join(args.output_dir , lowerCAmelCase__ ) accelerator.save_state(lowerCAmelCase__ ) model.eval() __a = 0 __a = 0 for step, batch in enumerate(lowerCAmelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. __a = {k: v.to(accelerator.device ) for k, v in batch.items()} __a = (batch['''image'''] - mean) / std with torch.no_grad(): __a = model(lowerCAmelCase__ ) __a = outputs.argmax(dim=-1 ) __a , __a = accelerator.gather_for_metrics((predictions, batch['''label''']) ) __a = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() __a = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}: {100 * eval_metric:.2f}''' ) if args.with_tracking: accelerator.log( { '''accuracy''': 100 * eval_metric, '''train_loss''': total_loss.item() / len(lowerCAmelCase__ ), '''epoch''': epoch, } , step=lowerCAmelCase__ , ) if checkpointing_steps == "epoch": __a = f'''epoch_{epoch}''' if args.output_dir is not None: __a = os.path.join(args.output_dir , lowerCAmelCase__ ) accelerator.save_state(lowerCAmelCase__ ) if args.with_tracking: accelerator.end_training() def lowercase ( ) -> int: __a = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument('''--data_dir''' , required=lowerCAmelCase__ , help='''The data folder on disk.''' ) parser.add_argument('''--fp16''' , action='''store_true''' , help='''If passed, will use FP16 training.''' ) parser.add_argument( '''--mixed_precision''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) parser.add_argument( '''--checkpointing_steps''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.''' , ) parser.add_argument( '''--output_dir''' , type=lowerCAmelCase__ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--resume_from_checkpoint''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''If the training should continue from a checkpoint folder.''' , ) parser.add_argument( '''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , ) parser.add_argument( '''--project_dir''' , type=lowerCAmelCase__ , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , ) __a = parser.parse_args() __a = {'''lr''': 3e-2, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 64, '''image_size''': 224} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
45
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : List[Any] ) -> Any: return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser('''download''' ) download_parser.add_argument( '''--cache-dir''' , type=_a , default=_a , help='''Path to location to store the models''' ) download_parser.add_argument( '''--force''' , action='''store_true''' , help='''Force the model to be download even if already in cache-dir''' ) download_parser.add_argument( '''--trust-remote-code''' , action='''store_true''' , help='''Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine''' , ) download_parser.add_argument('''model''' , type=_a , help='''Name of the model to download''' ) download_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a ): __a = model __a = cache __a = force __a = trust_remote_code def __UpperCAmelCase ( self ): from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
45
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
45
1
"""simple docstring""" import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( '''split_dict''' , [ SplitDict(), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1337 , num_examples=42 , dataset_name='''my_dataset''' )} ), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1337 , num_examples=42 )} ), SplitDict({'''train''': SplitInfo()} ), ] , ) def lowercase ( lowerCAmelCase__ : SplitDict ) -> List[Any]: __a = split_dict._to_yaml_list() assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ) __a = SplitDict._from_yaml_list(lowerCAmelCase__ ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump __a = None # the split name of split_dict takes over the name of the split info object __a = split_name assert split_dict == reloaded @pytest.mark.parametrize( '''split_info''' , [SplitInfo(), SplitInfo(dataset_name=lowerCAmelCase__ ), SplitInfo(dataset_name='''my_dataset''' )] ) def lowercase ( lowerCAmelCase__ : int ) -> List[str]: # For backward compatibility, we need asdict(split_dict) to return split info dictrionaries with the "dataset_name" # field even if it's deprecated. This way old versionso of `datasets` can still reload dataset_infos.json files __a = asdict(SplitDict({'''train''': split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
45
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = tempfile.mkdtemp() __a = BlipImageProcessor() __a = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' ) __a = BertTokenizerFast.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) __a = InstructBlipProcessor(_a , _a , _a ) processor.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , **_a ): return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).tokenizer def __UpperCAmelCase ( self , **_a ): return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def __UpperCAmelCase ( self , **_a ): return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).qformer_tokenizer def __UpperCAmelCase ( self ): shutil.rmtree(self.tmpdirname ) def __UpperCAmelCase ( self ): __a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __a = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def __UpperCAmelCase ( self ): __a = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) __a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __a = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) __a = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) self.assertIsInstance(processor.qformer_tokenizer , _a ) def __UpperCAmelCase ( self ): __a = self.get_image_processor() __a = self.get_tokenizer() __a = self.get_qformer_tokenizer() __a = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) __a = self.prepare_image_inputs() __a = image_processor(_a , return_tensors='''np''' ) __a = processor(images=_a , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __UpperCAmelCase ( self ): __a = self.get_image_processor() __a = self.get_tokenizer() __a = self.get_qformer_tokenizer() __a = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) __a = '''lower newer''' __a = processor(text=_a ) __a = tokenizer(_a , return_token_type_ids=_a ) __a = qformer_tokenizer(_a , return_token_type_ids=_a ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['''qformer_''' + key] ) def __UpperCAmelCase ( self ): __a = self.get_image_processor() __a = self.get_tokenizer() __a = self.get_qformer_tokenizer() __a = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) __a = '''lower newer''' __a = self.prepare_image_inputs() __a = processor(text=_a , images=_a ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , ) # test if it raises when no input is passed with pytest.raises(_a ): processor() def __UpperCAmelCase ( self ): __a = self.get_image_processor() __a = self.get_tokenizer() __a = self.get_qformer_tokenizer() __a = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) __a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a = processor.batch_decode(_a ) __a = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def __UpperCAmelCase ( self ): __a = self.get_image_processor() __a = self.get_tokenizer() __a = self.get_qformer_tokenizer() __a = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) __a = '''lower newer''' __a = self.prepare_image_inputs() __a = processor(text=_a , images=_a ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , )
45
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
1
"""simple docstring""" from __future__ import annotations lowercase_ = 1.6_021e-19 # units = C def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float , ) -> tuple[str, float]: if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif conductivity < 0: raise ValueError('''Conductivity cannot be negative''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative''' ) elif mobility < 0: raise ValueError('''mobility cannot be negative''' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int = 600851475143 ) -> int: try: __a = int(lowerCAmelCase__ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) __a = 2 __a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 __a = i while n % i == 0: __a = n // i i += 1 return int(lowerCAmelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
45
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = self._index.query(_a ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(_a , _a ) if len(_a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_a ) break else: self._duplicate_clusters[close_duplicates[0]].add(_a ) def __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase__ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__ ) ) , max_queue_size=100 ) ): di.add(lowerCAmelCase__ , lowerCAmelCase__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCAmelCase__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCAmelCase__ , lowerCAmelCase__ , ) , total=len(lowerCAmelCase__ ) , ): extremes_list.append(lowerCAmelCase__ ) return extremes_list def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = dataset.filter(lambda lowerCAmelCase__ , lowerCAmelCase__ : idx not in remove_indices , with_indices=lowerCAmelCase__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = extreme_dict[element['''base_index''']]['''copies'''] print(f'''Original dataset size: {len(lowerCAmelCase__ )}''' ) print(f'''Number of duplicate clusters: {len(lowerCAmelCase__ )}''' ) print(f'''Files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Unique files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Filtered dataset size: {len(lowerCAmelCase__ )}''' ) return ds_filter, duplicate_clusters
45
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file lowercase_ = "Run commands across TPU VMs for initial setup before running `accelerate launch`." def lowercase ( lowerCAmelCase__ : Optional[Any]=None ) -> Optional[int]: if subparsers is not None: __a = subparsers.add_parser('''tpu-config''' , description=_description ) else: __a = argparse.ArgumentParser('''Accelerate tpu-config command''' , description=_description ) # Core arguments __a = parser.add_argument_group( '''Config Arguments''' , '''Arguments that can be configured through `accelerate config`.''' ) config_args.add_argument( '''--config_file''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''Path to the config file to use for accelerate.''' , ) config_args.add_argument( '''--tpu_name''' , default=lowerCAmelCase__ , help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.''' , ) config_args.add_argument( '''--tpu_zone''' , default=lowerCAmelCase__ , help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.''' , ) __a = parser.add_argument_group('''TPU Arguments''' , '''Arguments for options ran inside the TPU.''' ) pod_args.add_argument( '''--use_alpha''' , action='''store_true''' , help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.''' , ) pod_args.add_argument( '''--command_file''' , default=lowerCAmelCase__ , help='''The path to the file containing the commands to run on the pod on startup.''' , ) pod_args.add_argument( '''--command''' , action='''append''' , nargs='''+''' , help='''A command to run on the pod. Can be passed multiple times.''' , ) pod_args.add_argument( '''--install_accelerate''' , action='''store_true''' , help='''Whether to install accelerate on the pod. Defaults to False.''' , ) pod_args.add_argument( '''--accelerate_version''' , default='''latest''' , help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.''' , ) pod_args.add_argument( '''--debug''' , action='''store_true''' , help='''If set, will print the command that would be run instead of running it.''' ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase__ ) return parser def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> Optional[Any]: __a = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase__ ): __a = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __a = defaults.command_file if not args.command and defaults.commands is not None: __a = defaults.commands if not args.tpu_name: __a = defaults.tpu_name if not args.tpu_zone: __a = defaults.tpu_zone if args.accelerate_version == "dev": __a = '''git+https://github.com/huggingface/accelerate.git''' elif args.accelerate_version == "latest": __a = '''accelerate -U''' elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase__ ): __a = f'''accelerate=={args.accelerate_version}''' if not args.command_file and not args.command: raise ValueError('''You must specify either a command file or a command to run on the pod.''' ) if args.command_file: with open(args.command_file , '''r''' ) as f: __a = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase__ ): __a = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __a = ['''cd /usr/share'''] if args.install_accelerate: new_cmd += [f'''pip install {args.accelerate_version}'''] new_cmd += args.command __a = '''; '''.join(lowerCAmelCase__ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __a = ['''gcloud'''] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f'''Running {' '.join(lowerCAmelCase__ )}''' ) return subprocess.run(lowerCAmelCase__ ) print('''Successfully setup pod.''' ) def lowercase ( ) -> str: __a = tpu_command_parser() __a = parser.parse_args() tpu_command_launcher(lowerCAmelCase__ )
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/config.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/config.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/config.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/config.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json", "roberta-large-openai-detector": "https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = 'roberta' def __init__( self , _a=50_265 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=1 , _a=0 , _a=2 , _a="absolute" , _a=True , _a=None , **_a , ): super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = use_cache __a = classifier_dropout class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCAmelCase ( self ): if self.task == "multiple-choice": __a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
45
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
1
"""simple docstring""" import torch from torch import nn class __lowerCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a=1 , _a=False ): super().__init__() __a = n_token __a = d_embed __a = d_proj __a = cutoffs + [n_token] __a = [0] + self.cutoffs __a = div_val __a = self.cutoffs[0] __a = len(self.cutoffs ) - 1 __a = self.shortlist_size + self.n_clusters if self.n_clusters > 0: __a = nn.Parameter(torch.zeros(self.n_clusters , self.d_embed ) ) __a = nn.Parameter(torch.zeros(self.n_clusters ) ) __a = nn.ModuleList() __a = nn.ParameterList() if div_val == 1: for i in range(len(self.cutoffs ) ): if d_proj != d_embed: self.out_projs.append(nn.Parameter(torch.FloatTensor(_a , _a ) ) ) else: self.out_projs.append(_a ) self.out_layers.append(nn.Linear(_a , _a ) ) else: for i in range(len(self.cutoffs ) ): __a , __a = self.cutoff_ends[i], self.cutoff_ends[i + 1] __a = d_embed // (div_val**i) self.out_projs.append(nn.Parameter(torch.FloatTensor(_a , _a ) ) ) self.out_layers.append(nn.Linear(_a , r_idx - l_idx ) ) __a = keep_order def __UpperCAmelCase ( self , _a , _a , _a , _a ): if proj is None: __a = nn.functional.linear(_a , _a , bias=_a ) else: # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1: __a = nn.functional.linear(_a , proj.t().contiguous() ) __a = nn.functional.linear(_a , _a , bias=_a ) # else: # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t())) # if bias is not None: # logit = logit + bias return logit def __UpperCAmelCase ( self , _a , _a=None , _a=False ): if labels is not None: # Shift so that tokens < n predict n __a = hidden[..., :-1, :].contiguous() __a = labels[..., 1:].contiguous() __a = hidden.view(-1 , hidden.size(-1 ) ) __a = labels.view(-1 ) if hidden.size(0 ) != labels.size(0 ): raise RuntimeError('''Input and labels should have the same size in the batch dimension.''' ) else: __a = hidden.view(-1 , hidden.size(-1 ) ) if self.n_clusters == 0: __a = self._compute_logit(_a , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) if labels is not None: __a = labels != -100 __a = torch.zeros_like(_a , dtype=hidden.dtype , device=hidden.device ) __a = ( -nn.functional.log_softmax(_a , dim=-1 )[mask].gather(1 , labels[mask].unsqueeze(1 ) ).squeeze(1 ) ) else: __a = nn.functional.log_softmax(_a , dim=-1 ) else: # construct weights and biases __a , __a = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: __a , __a = self.cutoff_ends[i], self.cutoff_ends[i + 1] __a = self.out_layers[0].weight[l_idx:r_idx] __a = self.out_layers[0].bias[l_idx:r_idx] else: __a = self.out_layers[i].weight __a = self.out_layers[i].bias if i == 0: __a = torch.cat([weight_i, self.cluster_weight] , dim=0 ) __a = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(_a ) biases.append(_a ) __a , __a , __a = weights[0], biases[0], self.out_projs[0] __a = self._compute_logit(_a , _a , _a , _a ) __a = nn.functional.log_softmax(_a , dim=1 ) if labels is None: __a = hidden.new_empty((head_logit.size(0 ), self.n_token) ) else: __a = torch.zeros_like(_a , dtype=hidden.dtype , device=hidden.device ) __a = 0 __a = [0] + self.cutoffs for i in range(len(_a ) - 1 ): __a , __a = cutoff_values[i], cutoff_values[i + 1] if labels is not None: __a = (labels >= l_idx) & (labels < r_idx) __a = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue __a = labels.index_select(0 , _a ) - l_idx __a = head_logprob.index_select(0 , _a ) __a = hidden.index_select(0 , _a ) else: __a = hidden if i == 0: if labels is not None: __a = head_logprob_i.gather(1 , target_i[:, None] ).squeeze(1 ) else: __a = head_logprob[:, : self.cutoffs[0]] else: __a , __a , __a = weights[i], biases[i], self.out_projs[i] __a = self._compute_logit(_a , _a , _a , _a ) __a = nn.functional.log_softmax(_a , dim=1 ) __a = self.cutoffs[0] + i - 1 # No probability for the head cluster if labels is not None: __a = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather( 1 , target_i[:, None] ).squeeze(1 ) else: __a = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i __a = logprob_i if labels is not None: if (hasattr(self , '''keep_order''' ) and self.keep_order) or keep_order: out.index_copy_(0 , _a , -logprob_i ) else: out[offset : offset + logprob_i.size(0 )].copy_(-logprob_i ) offset += logprob_i.size(0 ) return out def __UpperCAmelCase ( self , _a ): if self.n_clusters == 0: __a = self._compute_logit(_a , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) return nn.functional.log_softmax(_a , dim=-1 ) else: # construct weights and biases __a , __a = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: __a , __a = self.cutoff_ends[i], self.cutoff_ends[i + 1] __a = self.out_layers[0].weight[l_idx:r_idx] __a = self.out_layers[0].bias[l_idx:r_idx] else: __a = self.out_layers[i].weight __a = self.out_layers[i].bias if i == 0: __a = torch.cat([weight_i, self.cluster_weight] , dim=0 ) __a = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(_a ) biases.append(_a ) __a , __a , __a = weights[0], biases[0], self.out_projs[0] __a = self._compute_logit(_a , _a , _a , _a ) __a = hidden.new_empty((head_logit.size(0 ), self.n_token) ) __a = nn.functional.log_softmax(_a , dim=1 ) __a = [0] + self.cutoffs for i in range(len(_a ) - 1 ): __a , __a = cutoff_values[i], cutoff_values[i + 1] if i == 0: __a = head_logprob[:, : self.cutoffs[0]] else: __a , __a , __a = weights[i], biases[i], self.out_projs[i] __a = self._compute_logit(_a , _a , _a , _a ) __a = nn.functional.log_softmax(_a , dim=1 ) __a = head_logprob[:, -i] + tail_logprob_i __a = logprob_i return out
45
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
1
"""simple docstring""" import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): debug_launcher(test_script.main ) def __UpperCAmelCase ( self ): debug_launcher(test_ops.main )
45
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from collections.abc import Generator def lowercase ( ) -> Generator[int, None, None]: __a , __a = 0, 1 while True: __a , __a = b, a + b yield b def lowercase ( lowerCAmelCase__ : int = 1000 ) -> int: __a = 1 __a = fibonacci_generator() while len(str(next(lowerCAmelCase__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : torch.FloatTensor __UpperCAmelCase : torch.FloatTensor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = 1 @register_to_config def __init__( self , _a = 2_000 , _a = 0.15 , _a = 0.01 , _a = 1348.0 , _a = 1E-5 , _a = 1 , ): # standard deviation of the initial noise distribution __a = sigma_max # setable values __a = None self.set_sigmas(_a , _a , _a , _a ) def __UpperCAmelCase ( self , _a , _a = None ): return sample def __UpperCAmelCase ( self , _a , _a = None , _a = None ): __a = sampling_eps if sampling_eps is not None else self.config.sampling_eps __a = torch.linspace(1 , _a , _a , device=_a ) def __UpperCAmelCase ( self , _a , _a = None , _a = None , _a = None ): __a = sigma_min if sigma_min is not None else self.config.sigma_min __a = sigma_max if sigma_max is not None else self.config.sigma_max __a = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(_a , _a ) __a = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) __a = torch.exp(torch.linspace(math.log(_a ) , math.log(_a ) , _a ) ) __a = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def __UpperCAmelCase ( self , _a , _a ): return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def __UpperCAmelCase ( self , _a , _a , _a , _a = None , _a = True , ): if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) __a = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) __a = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda __a = timesteps.to(self.discrete_sigmas.device ) __a = self.discrete_sigmas[timesteps].to(sample.device ) __a = self.get_adjacent_sigma(_a , _a ).to(sample.device ) __a = torch.zeros_like(_a ) __a = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods __a = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): __a = diffusion.unsqueeze(-1 ) __a = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of __a = randn_tensor( sample.shape , layout=sample.layout , generator=_a , device=sample.device , dtype=sample.dtype ) __a = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? __a = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=_a , prev_sample_mean=_a ) def __UpperCAmelCase ( self , _a , _a , _a = None , _a = True , ): if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction __a = randn_tensor(sample.shape , layout=sample.layout , generator=_a ).to(sample.device ) # compute step size from the model_output, the noise, and the snr __a = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() __a = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() __a = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 __a = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term __a = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): __a = step_size.unsqueeze(-1 ) __a = sample + step_size * model_output __a = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __UpperCAmelCase ( self , _a , _a , _a , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __a = timesteps.to(original_samples.device ) __a = self.discrete_sigmas.to(original_samples.device )[timesteps] __a = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(_a ) * sigmas[:, None, None, None] ) __a = noise + original_samples return noisy_samples def __len__( self ): return self.config.num_train_timesteps
45
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('''The given input must be positive''' ) # get the generated string sequence __a = gray_code_sequence_string(lowerCAmelCase__ ) # # convert them to integers for i in range(len(lowerCAmelCase__ ) ): __a = int(sequence[i] , 2 ) return sequence def lowercase ( lowerCAmelCase__ : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __a = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __a = gray_code_sequence_string(bit_count - 1 ) __a = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __a = '''0''' + smaller_sequence[i] sequence.append(lowerCAmelCase__ ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __a = '''1''' + smaller_sequence[i] sequence.append(lowerCAmelCase__ ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
1
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = self._index.query(_a ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(_a , _a ) if len(_a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_a ) break else: self._duplicate_clusters[close_duplicates[0]].add(_a ) def __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase__ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__ ) ) , max_queue_size=100 ) ): di.add(lowerCAmelCase__ , lowerCAmelCase__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCAmelCase__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCAmelCase__ , lowerCAmelCase__ , ) , total=len(lowerCAmelCase__ ) , ): extremes_list.append(lowerCAmelCase__ ) return extremes_list def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = dataset.filter(lambda lowerCAmelCase__ , lowerCAmelCase__ : idx not in remove_indices , with_indices=lowerCAmelCase__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = extreme_dict[element['''base_index''']]['''copies'''] print(f'''Original dataset size: {len(lowerCAmelCase__ )}''' ) print(f'''Number of duplicate clusters: {len(lowerCAmelCase__ )}''' ) print(f'''Files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Unique files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Filtered dataset size: {len(lowerCAmelCase__ )}''' ) return ds_filter, duplicate_clusters
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
1
"""simple docstring""" from heapq import heappop, heappush import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : tuple[int, int] , lowerCAmelCase__ : tuple[int, int] , lowerCAmelCase__ : bool , ) -> tuple[float | int, list[tuple[int, int]]]: __a , __a = grid.shape __a = [-1, 1, 0, 0] __a = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __a , __a = [(0, source)], set() __a = np.full((rows, cols) , np.inf ) __a = 0 __a = np.empty((rows, cols) , dtype=lowerCAmelCase__ ) __a = None while queue: ((__a) , (__a)) = heappop(lowerCAmelCase__ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __a = [] while (x, y) != source: path.append((x, y) ) __a , __a = predecessors[x, y] path.append(lowerCAmelCase__ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(lowerCAmelCase__ ) ): __a , __a = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __a = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(lowerCAmelCase__ , (dist + 1, (nx, ny)) ) __a = dist + 1 __a = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json", "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json", "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json", "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json", "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json", "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json", "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json", "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json", "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json", "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = 'rwkv' __UpperCAmelCase : Optional[Any] = {'max_position_embeddings': 'context_length'} def __init__( self , _a=50_277 , _a=1_024 , _a=4_096 , _a=32 , _a=None , _a=None , _a=1E-5 , _a=0 , _a=0 , _a=6 , _a=False , _a=True , **_a , ): __a = vocab_size __a = context_length __a = hidden_size __a = num_hidden_layers __a = attention_hidden_size if attention_hidden_size is not None else hidden_size __a = intermediate_size if intermediate_size is not None else 4 * hidden_size __a = layer_norm_epsilon __a = rescale_every __a = use_cache __a = bos_token_id __a = eos_token_id super().__init__( tie_word_embeddings=_a , bos_token_id=_a , eos_token_id=_a , **_a )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" import math import unittest def lowercase ( lowerCAmelCase__ : int ) -> bool: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def __UpperCAmelCase ( self ): with self.assertRaises(_a ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , '''Zero doesn\'t have any positive factors, primes must have exactly two.''' , ) self.assertFalse( is_prime(1 ) , '''One only has 1 positive factor, primes must have exactly two.''' , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
45
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
1
"""simple docstring""" import inspect import unittest from math import floor from transformers import CvtConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device 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 CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , '''embed_dim''' ) ) self.parent.assertTrue(hasattr(_a , '''num_heads''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=3 , _a=[16, 48, 96] , _a=[1, 3, 6] , _a=[1, 2, 10] , _a=[7, 3, 3] , _a=[4, 2, 2] , _a=[2, 1, 1] , _a=[2, 2, 2] , _a=[False, False, True] , _a=[0.0, 0.0, 0.0] , _a=0.02 , _a=1E-12 , _a=True , _a=True , _a=2 , ): __a = parent __a = batch_size __a = image_size __a = patch_sizes __a = patch_stride __a = patch_padding __a = is_training __a = use_labels __a = num_labels __a = num_channels __a = embed_dim __a = num_heads __a = stride_kv __a = depth __a = cls_token __a = attention_drop_rate __a = initializer_range __a = layer_norm_eps def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = CvtModel(config=_a ) model.to(_a ) model.eval() __a = model(_a ) __a = (self.image_size, self.image_size) __a , __a = image_size[0], image_size[1] for i in range(len(self.depth ) ): __a = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) __a = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = self.num_labels __a = CvtForImageClassification(_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 ): __a = self.prepare_config_and_inputs() __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = (CvtModel, CvtForImageClassification) if is_torch_available() else () __UpperCAmelCase : List[Any] = ( {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase : Any = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = CvtModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCAmelCase ( self ): return @unittest.skip(reason='''Cvt does not output attentions''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''Cvt does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''Cvt does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __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 ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __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 = len(self.model_tester.depth ) self.assertEqual(len(_a ) , _a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __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 ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CvtModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> Optional[Any]: __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self ): __a = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).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, 1_000) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([0.9285, 0.9015, -0.3150] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) )
45
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
1
"""simple docstring""" from collections import deque class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a ): __a = process_name # process name __a = arrival_time # arrival time of the process # completion time of finished process or last interrupted time __a = arrival_time __a = burst_time # remaining burst time __a = 0 # total time of the process wait in ready queue __a = 0 # time from arrival time to completion time class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a , _a , ): # total number of mlfq's queues __a = number_of_queues # time slice of queues that round robin algorithm applied __a = time_slices # unfinished process is in this ready_queue __a = queue # current time __a = current_time # finished process is in this sequence queue __a = deque() def __UpperCAmelCase ( self ): __a = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def __UpperCAmelCase ( self , _a ): __a = [] for i in range(len(_a ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def __UpperCAmelCase ( self , _a ): __a = [] for i in range(len(_a ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def __UpperCAmelCase ( self , _a ): __a = [] for i in range(len(_a ) ): completion_times.append(queue[i].stop_time ) return completion_times def __UpperCAmelCase ( self , _a ): return [q.burst_time for q in queue] def __UpperCAmelCase ( self , _a ): process.waiting_time += self.current_time - process.stop_time return process.waiting_time def __UpperCAmelCase ( self , _a ): __a = deque() # sequence deque of finished process while len(_a ) != 0: __a = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(_a ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 __a = 0 # set the process's turnaround time because it is finished __a = self.current_time - cp.arrival_time # set the completion time __a = self.current_time # add the process to queue that has finished queue finished.append(_a ) self.finish_queue.extend(_a ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def __UpperCAmelCase ( self , _a , _a ): __a = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(_a ) ): __a = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(_a ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time __a = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(_a ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished __a = 0 # set the finish time __a = self.current_time # update the process' turnaround time because it is finished __a = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(_a ) self.finish_queue.extend(_a ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def __UpperCAmelCase ( self ): # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): __a , __a = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest lowercase_ = Process("P1", 0, 5_3) lowercase_ = Process("P2", 0, 1_7) lowercase_ = Process("P3", 0, 6_8) lowercase_ = Process("P4", 0, 2_4) lowercase_ = 3 lowercase_ = [1_7, 2_5] lowercase_ = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"queue": deque([Pa, Pa, Pa, Pa])}) lowercase_ = Process("P1", 0, 5_3) lowercase_ = Process("P2", 0, 1_7) lowercase_ = Process("P3", 0, 6_8) lowercase_ = Process("P4", 0, 2_4) lowercase_ = 3 lowercase_ = [1_7, 2_5] lowercase_ = deque([Pa, Pa, Pa, Pa]) lowercase_ = MLFQ(number_of_queues, time_slices, queue, 0) lowercase_ = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F'''waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print completion times of processes(P1, P2, P3, P4) print( F'''completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print total turnaround times of processes(P1, P2, P3, P4) print( F'''turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print sequence of finished processes print( F'''sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}''' )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class __lowerCAmelCase : '''simple docstring''' def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = UNetaDConditionModel( sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __a = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=_a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __a = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = UNetaDConditionModel( sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , class_embed_type='''timestep''' , mid_block_scale_factor=1.414 , time_embedding_act_fn='''gelu''' , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __a = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=_a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __a = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , ) torch.manual_seed(0 ) __a = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def __UpperCAmelCase ( self ): __a = self.get_dummy_components() __a = self.pipeline_class(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = self.get_dummy_inputs(_a ) __a = inputs['''prompt'''] __a = inputs['''generator'''] __a = inputs['''num_inference_steps'''] __a = inputs['''output_type'''] if "image" in inputs: __a = inputs['''image'''] else: __a = None if "mask_image" in inputs: __a = inputs['''mask_image'''] else: __a = None if "original_image" in inputs: __a = inputs['''original_image'''] else: __a = None __a , __a = pipe.encode_prompt(_a ) # inputs with prompt converted to embeddings __a = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __a = image if mask_image is not None: __a = mask_image if original_image is not None: __a = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(_a , _a , _a ) __a = pipe(**_a )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_a ) __a = self.pipeline_class.from_pretrained(_a ) pipe_loaded.to(_a ) pipe_loaded.set_progress_bar_config(disable=_a ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(_a , _a ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) __a = self.get_dummy_inputs(_a ) __a = inputs['''generator'''] __a = inputs['''num_inference_steps'''] __a = inputs['''output_type'''] # inputs with prompt converted to embeddings __a = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __a = image if mask_image is not None: __a = mask_image if original_image is not None: __a = original_image __a = pipe_loaded(**_a )[0] __a = np.abs(to_np(_a ) - to_np(_a ) ).max() self.assertLess(_a , 1E-4 ) def __UpperCAmelCase ( self ): __a = self.get_dummy_components() __a = self.pipeline_class(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = self.get_dummy_inputs(_a ) __a = pipe(**_a )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_a ) __a = self.pipeline_class.from_pretrained(_a ) pipe_loaded.to(_a ) pipe_loaded.set_progress_bar_config(disable=_a ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests __a = self.get_dummy_inputs(_a ) __a = pipe_loaded(**_a )[0] __a = np.abs(to_np(_a ) - to_np(_a ) ).max() self.assertLess(_a , 1E-4 )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
1
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=False , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=64 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=2 , _a=2 , _a=2 , _a=2 , _a=4 , _a=1 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = q_groups __a = k_groups __a = v_groups __a = post_attention_groups __a = intermediate_groups __a = output_groups def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = SqueezeBertModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , _a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = SqueezeBertForMaskedLM(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = SqueezeBertForQuestionAnswering(config=_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , start_positions=_a , end_positions=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = SqueezeBertForSequenceClassification(_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = SqueezeBertForTokenClassification(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = SqueezeBertForMultipleChoice(config=_a ) model.to(_a ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( _a , attention_mask=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a)) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Tuple = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase : int = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : Dict = False def __UpperCAmelCase ( self ): __a = SqueezeBertModelTester(self ) __a = ConfigTester(self , config_class=_a , dim=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = SqueezeBertModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_sentencepiece @require_tokenizers @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = SqueezeBertForSequenceClassification.from_pretrained('''squeezebert/squeezebert-mnli''' ) __a = torch.tensor([[1, 29_414, 232, 328, 740, 1_140, 12_695, 69, 13, 1_588, 2]] ) __a = model(_a )[0] __a = torch.Size((1, 3) ) self.assertEqual(output.shape , _a ) __a = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(_a , _a , atol=1E-4 ) )
45
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import pprint import requests lowercase_ = "https://zenquotes.io/api" def lowercase ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def lowercase ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": lowercase_ = random_quotes() pprint.pprint(response)
45
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
45
1
"""simple docstring""" import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=6 , _a=17 , _a=23 , _a=11 , _a=True , ): __a = parent __a = batch_size __a = seq_length __a = act_dim __a = state_dim __a = hidden_size __a = max_length __a = is_training def __UpperCAmelCase ( self ): __a = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) __a = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) __a = floats_tensor((self.batch_size, self.seq_length, 1) ) __a = floats_tensor((self.batch_size, self.seq_length, 1) ) __a = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1_000 ) __a = random_attention_mask((self.batch_size, self.seq_length) ) __a = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def __UpperCAmelCase ( self ): return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): __a = DecisionTransformerModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , _a , _a , _a , _a , _a ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = { '''states''': states, '''actions''': actions, '''rewards''': rewards, '''returns_to_go''': returns_to_go, '''timesteps''': timesteps, '''attention_mask''': attention_mask, } return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any = (DecisionTransformerModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = () __UpperCAmelCase : Any = {'feature-extraction': DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids __UpperCAmelCase : int = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : int = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : int = False __UpperCAmelCase : int = False __UpperCAmelCase : Dict = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self ): __a = DecisionTransformerModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = DecisionTransformerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __UpperCAmelCase ( self ): __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 = [ '''states''', '''actions''', '''rewards''', '''returns_to_go''', '''timesteps''', '''attention_mask''', ] self.assertListEqual(arg_names[: len(_a )] , _a ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = 2 # number of steps of autoregressive prediction we will perform __a = 10 # defined by the RL environment, may be normalized __a = DecisionTransformerModel.from_pretrained('''edbeeching/decision-transformer-gym-hopper-expert''' ) __a = model.to(_a ) __a = model.config torch.manual_seed(0 ) __a = torch.randn(1 , 1 , config.state_dim ).to(device=_a , dtype=torch.floataa ) # env.reset() __a = torch.tensor( [[0.24_2793, -0.2869_3074, 0.874_2613], [0.6781_5274, -0.0810_1085, -0.1295_2147]] , device=_a ) __a = torch.tensor(_a , device=_a , dtype=torch.floataa ).reshape(1 , 1 , 1 ) __a = state __a = torch.zeros(1 , 0 , config.act_dim , device=_a , dtype=torch.floataa ) __a = torch.zeros(1 , 0 , device=_a , dtype=torch.floataa ) __a = torch.tensor(0 , device=_a , dtype=torch.long ).reshape(1 , 1 ) for step in range(_a ): __a = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=_a )] , dim=1 ) __a = torch.cat([rewards, torch.zeros(1 , 1 , device=_a )] , dim=1 ) __a = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): __a , __a , __a = model( states=_a , actions=_a , rewards=_a , returns_to_go=_a , timesteps=_a , attention_mask=_a , return_dict=_a , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) __a , __a , __a , __a = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=_a , dtype=torch.floataa ), 1.0, False, {}, ) __a = action_pred[0, -1] __a = torch.cat([states, state] , dim=1 ) __a = returns_to_go[0, -1] - reward __a = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) __a = torch.cat( [timesteps, torch.ones((1, 1) , device=_a , dtype=torch.long ) * (step + 1)] , dim=1 )
45
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder lowercase_ = datasets.utils.logging.get_logger(__name__) class __lowerCAmelCase ( folder_based_builder.FolderBasedBuilderConfig ): '''simple docstring''' __UpperCAmelCase : bool = None __UpperCAmelCase : bool = None class __lowerCAmelCase ( folder_based_builder.FolderBasedBuilder ): '''simple docstring''' __UpperCAmelCase : Dict = datasets.Audio() __UpperCAmelCase : Optional[Any] = 'audio' __UpperCAmelCase : Union[str, Any] = AudioFolderConfig __UpperCAmelCase : List[str] # definition at the bottom of the script __UpperCAmelCase : Optional[Any] = AudioClassification(audio_column='audio' , label_column='label' ) lowercase_ = [ ".aiff", ".au", ".avr", ".caf", ".flac", ".htk", ".svx", ".mat4", ".mat5", ".mpc2k", ".ogg", ".paf", ".pvf", ".raw", ".rf64", ".sd2", ".sds", ".ircam", ".voc", ".w64", ".wav", ".nist", ".wavex", ".wve", ".xi", ".mp3", ".opus", ] lowercase_ = AUDIO_EXTENSIONS
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
1
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} lowercase_ = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } lowercase_ = { "gpt-neox-20b": 2_0_4_8, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = ['input_ids', 'attention_mask'] def __init__( self , _a=None , _a=None , _a=None , _a="<|endoftext|>" , _a="<|endoftext|>" , _a="<|endoftext|>" , _a=False , **_a , ): super().__init__( _a , _a , tokenizer_file=_a , unk_token=_a , bos_token=_a , eos_token=_a , add_prefix_space=_a , **_a , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , _a ) != add_prefix_space: __a = getattr(_a , pre_tok_state.pop('''type''' ) ) __a = add_prefix_space __a = pre_tok_class(**_a ) __a = add_prefix_space def __UpperCAmelCase ( self , _a , _a = None ): __a = self._tokenizer.model.save(_a , name=_a ) return tuple(_a ) def __UpperCAmelCase ( self , _a ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_a , add_special_tokens=_a ) + [self.eos_token_id] ) if len(_a ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
45
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
1
"""simple docstring""" import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): # A mock response for an HTTP head request to emulate server down __a = mock.Mock() __a = 500 __a = {} __a = HTTPError __a = {} # Download this model to make sure it's in the cache. __a = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=_a ) as mock_head: __a = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def __UpperCAmelCase ( self ): # A mock response for an HTTP head request to emulate server down __a = mock.Mock() __a = 500 __a = {} __a = HTTPError __a = {} # Download this model to make sure it's in the cache. __a = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=_a ) as mock_head: __a = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # This check we did call the fake head request mock_head.assert_called() def __UpperCAmelCase ( self ): # This test is for deprecated behavior and can be removed in v5 try: __a = tempfile.mktemp() with open(_a , '''wb''' ) as f: http_get('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' , _a ) __a = AlbertTokenizer.from_pretrained(_a ) finally: os.remove(_a ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('''tokenizer.json''' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('''tokenizer.json''' , '''wb''' ) as f: http_get('''https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json''' , _a ) __a = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1_000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('''tokenizer.json''' ) def __UpperCAmelCase ( self ): # This test is for deprecated behavior and can be removed in v5 __a = AlbertTokenizer.from_pretrained('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' ) @is_staging_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def __UpperCAmelCase ( cls ): __a = TOKEN HfFolder.save_token(_a ) @classmethod def __UpperCAmelCase ( cls ): try: delete_repo(token=cls._token , repo_id='''test-tokenizer''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-tokenizer-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-tokenizer''' ) except HTTPError: pass def __UpperCAmelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: __a = os.path.join(_a , '''vocab.txt''' ) with open(_a , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) __a = BertTokenizer(_a ) tokenizer.push_to_hub('''test-tokenizer''' , use_auth_token=self._token ) __a = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''test-tokenizer''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_a , repo_id='''test-tokenizer''' , push_to_hub=_a , use_auth_token=self._token ) __a = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def __UpperCAmelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: __a = os.path.join(_a , '''vocab.txt''' ) with open(_a , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) __a = BertTokenizer(_a ) tokenizer.push_to_hub('''valid_org/test-tokenizer-org''' , use_auth_token=self._token ) __a = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-tokenizer-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( _a , repo_id='''valid_org/test-tokenizer-org''' , push_to_hub=_a , use_auth_token=self._token ) __a = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def __UpperCAmelCase ( self ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __a = os.path.join(_a , '''vocab.txt''' ) with open(_a , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) __a = CustomTokenizer(_a ) # No fast custom tokenizer tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) __a = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=_a ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __a = os.path.join(_a , '''vocab.txt''' ) with open(_a , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) __a = BertTokenizerFast.from_pretrained(_a ) bert_tokenizer.save_pretrained(_a ) __a = CustomTokenizerFast.from_pretrained(_a ) tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) __a = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=_a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizerFast''' ) __a = AutoTokenizer.from_pretrained( f'''{USER}/test-dynamic-tokenizer''' , use_fast=_a , trust_remote_code=_a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = Trie() trie.add('''Hello 友達''' ) self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) trie.add('''Hello''' ) trie.data self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {'''''': 1, ''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) def __UpperCAmelCase ( self ): __a = Trie() self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS] This is a extra_id_100'''] ) trie.add('''[CLS]''' ) trie.add('''extra_id_1''' ) trie.add('''extra_id_100''' ) self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS]''', ''' This is a ''', '''extra_id_100'''] ) def __UpperCAmelCase ( self ): __a = Trie() trie.add('''A''' ) self.assertEqual(trie.split('''ABC''' ) , ['''A''', '''BC'''] ) self.assertEqual(trie.split('''BCA''' ) , ['''BC''', '''A'''] ) def __UpperCAmelCase ( self ): __a = Trie() trie.add('''TOKEN]''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def __UpperCAmelCase ( self ): __a = Trie() trie.add('''A''' ) trie.add('''P''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def __UpperCAmelCase ( self ): __a = Trie() trie.add('''AB''' ) trie.add('''B''' ) trie.add('''C''' ) self.assertEqual(trie.split('''ABC''' ) , ['''AB''', '''C'''] ) def __UpperCAmelCase ( self ): __a = Trie() trie.add('''ABC''' ) trie.add('''B''' ) trie.add('''CD''' ) self.assertEqual(trie.split('''ABCD''' ) , ['''ABC''', '''D'''] ) def __UpperCAmelCase ( self ): # Even if the offsets are wrong, we necessarily output correct string # parts. __a = Trie() __a = trie.cut_text('''ABC''' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(_a , ['''AB''', '''C'''] )
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
1
"""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 lowercase_ = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Union[int, Iterable[int]] , lowerCAmelCase__ : bool , lowerCAmelCase__ : int ) -> Tuple[int, int]: def constraint_to_multiple_of(lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str]=0 , lowerCAmelCase__ : List[str]=None ): __a = round(val / multiple ) * multiple if max_val is not None and x > max_val: __a = math.floor(val / multiple ) * multiple if x < min_val: __a = math.ceil(val / multiple ) * multiple return x __a = (output_size, output_size) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else output_size __a , __a = get_image_size(lowerCAmelCase__ ) __a , __a = output_size # determine new height and width __a = output_height / input_height __a = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __a = scale_width else: # fit height __a = scale_height __a = constraint_to_multiple_of(scale_height * input_height , multiple=lowerCAmelCase__ ) __a = constraint_to_multiple_of(scale_width * input_width , multiple=lowerCAmelCase__ ) return (new_height, new_width) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = ['pixel_values'] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = False , _a = 1 , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , **_a , ): super().__init__(**_a ) __a = size if size is not None else {'''height''': 384, '''width''': 384} __a = get_size_dict(_a ) __a = do_resize __a = size __a = keep_aspect_ratio __a = ensure_multiple_of __a = resample __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __a = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCAmelCase ( self , _a , _a , _a = False , _a = 1 , _a = PILImageResampling.BICUBIC , _a = None , **_a , ): __a = get_size_dict(_a ) 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()}''' ) __a = get_resize_output_image_size( _a , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=_a , multiple=_a , ) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def __UpperCAmelCase ( self , _a , _a , _a = None , **_a , ): return rescale(_a , scale=_a , data_format=_a , **_a ) def __UpperCAmelCase ( self , _a , _a , _a , _a = None , **_a , ): return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def __UpperCAmelCase ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(_a ) __a = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __a = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __a = resample if resample is not None else self.resample __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_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. __a = [to_numpy_array(_a ) for image in images] if do_resize: __a = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_rescale: __a = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: __a = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] __a = [to_channel_dimension_format(_a , _a ) for image in images] __a = {'''pixel_values''': images} return BatchFeature(data=_a , tensor_type=_a ) def __UpperCAmelCase ( self , _a , _a = None ): __a = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(_a ) != len(_a ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(_a ): __a = target_sizes.numpy() __a = [] for idx in range(len(_a ) ): __a = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=_a ) __a = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_a ) else: __a = logits.argmax(dim=1 ) __a = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
45
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = self._index.query(_a ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(_a , _a ) if len(_a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_a ) break else: self._duplicate_clusters[close_duplicates[0]].add(_a ) def __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase__ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__ ) ) , max_queue_size=100 ) ): di.add(lowerCAmelCase__ , lowerCAmelCase__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCAmelCase__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCAmelCase__ , lowerCAmelCase__ , ) , total=len(lowerCAmelCase__ ) , ): extremes_list.append(lowerCAmelCase__ ) return extremes_list def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = dataset.filter(lambda lowerCAmelCase__ , lowerCAmelCase__ : idx not in remove_indices , with_indices=lowerCAmelCase__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = extreme_dict[element['''base_index''']]['''copies'''] print(f'''Original dataset size: {len(lowerCAmelCase__ )}''' ) print(f'''Number of duplicate clusters: {len(lowerCAmelCase__ )}''' ) print(f'''Files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Unique files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Filtered dataset size: {len(lowerCAmelCase__ )}''' ) return ds_filter, duplicate_clusters
45
1
"""simple docstring""" 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 lowercase_ = logging.get_logger(__name__) lowercase_ = { "google/efficientnet-b7": "https://huggingface.co/google/efficientnet-b7/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = 'efficientnet' def __init__( self , _a = 3 , _a = 600 , _a = 2.0 , _a = 3.1 , _a = 8 , _a = [3, 3, 5, 3, 5, 5, 3] , _a = [32, 16, 24, 40, 80, 112, 192] , _a = [16, 24, 40, 80, 112, 192, 320] , _a = [] , _a = [1, 2, 2, 2, 1, 2, 1] , _a = [1, 2, 2, 3, 3, 4, 1] , _a = [1, 6, 6, 6, 6, 6, 6] , _a = 0.25 , _a = "swish" , _a = 2_560 , _a = "mean" , _a = 0.02 , _a = 0.001 , _a = 0.99 , _a = 0.5 , _a = 0.2 , **_a , ): super().__init__(**_a ) __a = num_channels __a = image_size __a = width_coefficient __a = depth_coefficient __a = depth_divisor __a = kernel_sizes __a = in_channels __a = out_channels __a = depthwise_padding __a = strides __a = num_block_repeats __a = expand_ratios __a = squeeze_expansion_ratio __a = hidden_act __a = hidden_dim __a = pooling_type __a = initializer_range __a = batch_norm_eps __a = batch_norm_momentum __a = dropout_rate __a = drop_connect_rate __a = sum(_a ) * 4 class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-5
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""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_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , _a , _a=7 , _a=3 , _a=10 , _a=18 , _a=30 , _a=400 , _a=True , _a=None , _a=True , _a=[0.5, 0.5, 0.5] , _a=[0.5, 0.5, 0.5] , _a=None , ): __a = size if size is not None else {'''shortest_edge''': 18} __a = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} __a = parent __a = batch_size __a = num_channels __a = num_frames __a = image_size __a = min_resolution __a = max_resolution __a = do_resize __a = size __a = do_normalize __a = image_mean __a = image_std __a = crop_size def __UpperCAmelCase ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any = VivitImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self ): __a = VivitImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): __a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , '''image_mean''' ) ) self.assertTrue(hasattr(_a , '''image_std''' ) ) self.assertTrue(hasattr(_a , '''do_normalize''' ) ) self.assertTrue(hasattr(_a , '''do_resize''' ) ) self.assertTrue(hasattr(_a , '''do_center_crop''' ) ) self.assertTrue(hasattr(_a , '''size''' ) ) def __UpperCAmelCase ( self ): __a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) __a = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PIL videos __a = prepare_video_inputs(self.image_processor_tester , equal_resolution=_a ) for video in video_inputs: self.assertIsInstance(_a , _a ) self.assertIsInstance(video[0] , Image.Image ) # Test not batched input __a = image_processing(video_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __a = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a = prepare_video_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for video in video_inputs: self.assertIsInstance(_a , _a ) self.assertIsInstance(video[0] , np.ndarray ) # Test not batched input __a = image_processing(video_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __a = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __UpperCAmelCase ( self ): # Initialize image_processing __a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a = prepare_video_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for video in video_inputs: self.assertIsInstance(_a , _a ) self.assertIsInstance(video[0] , torch.Tensor ) # Test not batched input __a = image_processing(video_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __a = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
45
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowercase_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[str] = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The column name of the images in the files.'} ) __UpperCAmelCase : Optional[str] = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A folder containing the training data.'} ) __UpperCAmelCase : Optional[str] = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A folder containing the validation data.'} ) __UpperCAmelCase : Optional[float] = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) __UpperCAmelCase : Optional[int] = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) __UpperCAmelCase : Optional[int] = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def __UpperCAmelCase ( self ): __a = {} if self.train_dir is not None: __a = self.train_dir if self.validation_dir is not None: __a = self.validation_dir __a = data_files if data_files else None @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : str = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) __UpperCAmelCase : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) __UpperCAmelCase : str = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Name or path of preprocessor config.'} ) __UpperCAmelCase : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) __UpperCAmelCase : float = field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) __UpperCAmelCase : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : float = field( default=1e-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def lowercase ( lowerCAmelCase__ : int ) -> Tuple: __a = torch.stack([example['''pixel_values'''] for example in examples] ) return {"pixel_values": pixel_values} def lowercase ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __a = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __a , __a , __a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __a , __a , __a = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_mae''' , lowerCAmelCase__ , lowerCAmelCase__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __a = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase__ ) transformers.utils.logging.set_verbosity(lowerCAmelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. __a = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __a = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset. __a = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. __a = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , lowerCAmelCase__ ) and data_args.train_val_split > 0.0: __a = ds['''train'''].train_test_split(data_args.train_val_split ) __a = split['''train'''] __a = split['''test'''] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __a = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: __a = ViTMAEConfig.from_pretrained(model_args.config_name , **lowerCAmelCase__ ) elif model_args.model_name_or_path: __a = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) else: __a = ViTMAEConfig() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(f'''New config: {config}''' ) # adapt config config.update( { '''mask_ratio''': model_args.mask_ratio, '''norm_pix_loss''': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: __a = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **lowerCAmelCase__ ) elif model_args.model_name_or_path: __a = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) else: __a = ViTImageProcessor() # create model if model_args.model_name_or_path: __a = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=lowerCAmelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) __a = ViTMAEForPreTraining(lowerCAmelCase__ ) if training_args.do_train: __a = ds['''train'''].column_names else: __a = ds['''validation'''].column_names if data_args.image_column_name is not None: __a = data_args.image_column_name elif "image" in column_names: __a = '''image''' elif "img" in column_names: __a = '''img''' else: __a = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: __a = image_processor.size['''shortest_edge'''] else: __a = (image_processor.size['''height'''], image_processor.size['''width''']) __a = Compose( [ Lambda(lambda lowerCAmelCase__ : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(lowerCAmelCase__ , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(lowerCAmelCase__ : Union[str, Any] ): __a = [transforms(lowerCAmelCase__ ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: __a = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(lowerCAmelCase__ ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: __a = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(lowerCAmelCase__ ) # Compute absolute learning rate __a = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: __a = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer __a = Trainer( model=lowerCAmelCase__ , args=lowerCAmelCase__ , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=lowerCAmelCase__ , data_collator=lowerCAmelCase__ , ) # Training if training_args.do_train: __a = None if training_args.resume_from_checkpoint is not None: __a = training_args.resume_from_checkpoint elif last_checkpoint is not None: __a = last_checkpoint __a = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __a = trainer.evaluate() trainer.log_metrics('''eval''' , lowerCAmelCase__ ) trainer.save_metrics('''eval''' , lowerCAmelCase__ ) # Write model card and (optionally) push to hub __a = { '''tasks''': '''masked-auto-encoding''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-auto-encoding'''], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase__ ) else: trainer.create_model_card(**lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : List[Any] ) -> Tuple: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
45
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *_a , **_a ): super().__init__(*_a , **_a ) requires_backends(self , '''vision''' ) self.check_model_type(_a ) def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , **_a ): return {}, {}, {} def __UpperCAmelCase ( self , _a ): __a = load_image(_a ) __a = image.size __a = self.image_processor(images=_a , return_tensors=self.framework ) return model_inputs def __UpperCAmelCase ( self , _a ): __a = self.model(**_a ) return model_outputs def __UpperCAmelCase ( self , _a ): __a = model_outputs.predicted_depth __a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=_a ) __a = prediction.squeeze().cpu().numpy() __a = (output * 255 / np.max(_a )).astype('''uint8''' ) __a = Image.fromarray(_a ) __a = {} __a = predicted_depth __a = depth return output_dict
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @property def __UpperCAmelCase ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self ): __a = ort.SessionOptions() __a = False return options def __UpperCAmelCase ( self ): __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) __a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy''' ) # using the PNDM scheduler by default __a = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''onnx''' , safety_checker=_a , feature_extractor=_a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_a ) __a = '''A red cat sitting on a park bench''' __a = np.random.RandomState(0 ) __a = pipe( prompt=_a , image=_a , mask_image=_a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=_a , output_type='''np''' , ) __a = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
45
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> list[int]: if length <= 0 or not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(lowerCAmelCase__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=1_0))
45
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
1
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = ['image_processor', 'tokenizer'] __UpperCAmelCase : int = 'LayoutLMv3ImageProcessor' __UpperCAmelCase : List[str] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self , _a=None , _a=None , **_a ): __a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) __a = kwargs.pop('''feature_extractor''' ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = None , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) # first, apply the image processor __a = self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features['''words'''] __a = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values __a = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(_a , encoded_inputs['''overflow_to_sample_mapping'''] ) __a = images return encoded_inputs def __UpperCAmelCase ( self , _a , _a ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f''' {len(_a )} and {len(_a )}''' ) return images_with_overflow def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def __UpperCAmelCase ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
45
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
1
"""simple docstring""" import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowercase_ = { "facebook/mask2former-swin-small-coco-instance": ( "https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Dict = 'mask2former' __UpperCAmelCase : Dict = ['swin'] __UpperCAmelCase : Dict = {'hidden_size': 'hidden_dim'} def __init__( self , _a = None , _a = 256 , _a = 256 , _a = 256 , _a = 1_024 , _a = "relu" , _a = 6 , _a = 10 , _a = 8 , _a = 0.0 , _a = 2_048 , _a = False , _a = False , _a = 4 , _a = 255 , _a = 100 , _a = 0.1 , _a = 2.0 , _a = 5.0 , _a = 5.0 , _a = 12_544 , _a = 3.0 , _a = 0.75 , _a = 0.02 , _a = 1.0 , _a = True , _a = [4, 8, 16, 32] , _a = None , **_a , ): if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __a = CONFIG_MAPPING['''swin''']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_a , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(_a , _a ): __a = backbone_config.pop('''model_type''' ) __a = CONFIG_MAPPING[backbone_model_type] __a = config_class.from_dict(_a ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ''' f'''Supported model types: {','.join(self.backbones_supported )}''' ) __a = backbone_config __a = feature_size __a = mask_feature_size __a = hidden_dim __a = encoder_feedforward_dim __a = activation_function __a = encoder_layers __a = decoder_layers __a = num_attention_heads __a = dropout __a = dim_feedforward __a = pre_norm __a = enforce_input_projection __a = common_stride __a = ignore_value __a = num_queries __a = no_object_weight __a = class_weight __a = mask_weight __a = dice_weight __a = train_num_points __a = oversample_ratio __a = importance_sample_ratio __a = init_std __a = init_xavier_std __a = use_auxiliary_loss __a = feature_strides __a = output_auxiliary_logits __a = decoder_layers super().__init__(**_a ) @classmethod def __UpperCAmelCase ( cls , _a , **_a ): return cls( backbone_config=_a , **_a , ) def __UpperCAmelCase ( self ): __a = copy.deepcopy(self.__dict__ ) __a = self.backbone_config.to_dict() __a = self.__class__.model_type return output
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
1
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float ) -> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance < 0: raise ValueError('''Resistance cannot be negative''' ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
1
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: __a = ( f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = 1 __a = FrozenDict(_a ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: __a = ( f'''The configuration file of this scheduler: {scheduler} has not set the configuration''' ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , _a , standard_warn=_a ) __a = dict(scheduler.config ) __a = True __a = FrozenDict(_a ) if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=_a , segmentation_processor=_a , vae=_a , text_encoder=_a , tokenizer=_a , unet=_a , scheduler=_a , safety_checker=_a , feature_extractor=_a , ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __a = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __UpperCAmelCase ( self ): if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_a , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , _a , _a , _a , _a = 512 , _a = 512 , _a = 50 , _a = 7.5 , _a = None , _a = 1 , _a = 0.0 , _a = None , _a = None , _a = "pil" , _a = True , _a = None , _a = 1 , **_a , ): __a = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) __a = self.segmentation_model(**_a ) __a = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __a = self.numpy_to_pil(_a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __a = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_a , image=_a , mask_image=_a , height=_a , width=_a , num_inference_steps=_a , guidance_scale=_a , negative_prompt=_a , num_images_per_prompt=_a , eta=_a , generator=_a , latents=_a , output_type=_a , return_dict=_a , callback=_a , callback_steps=_a , )
45
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase_ = "\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n >>> repo = \"openai/shap-e-img2img\"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n >>> image = load_image(image_url).convert(\"RGB\")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n ```\n" @dataclass class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[PIL.Image.Image, np.ndarray] class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , ): super().__init__() self.register_modules( prior=_a , image_encoder=_a , image_processor=_a , scheduler=_a , renderer=_a , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): if latents is None: __a = randn_tensor(_a , generator=_a , device=_a , dtype=_a ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) __a = latents.to(_a ) __a = latents * scheduler.init_noise_sigma return latents def __UpperCAmelCase ( self , _a=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) __a = torch.device(f'''cuda:{gpu_id}''' ) __a = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property def __UpperCAmelCase ( self ): if self.device != torch.device('''meta''' ) or not hasattr(self.image_encoder , '''_hf_hook''' ): return self.device for module in self.image_encoder.modules(): if ( hasattr(_a , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def __UpperCAmelCase ( self , _a , _a , _a , _a , ): if isinstance(_a , _a ) and isinstance(image[0] , torch.Tensor ): __a = torch.cat(_a , axis=0 ) if image[0].ndim == 4 else torch.stack(_a , axis=0 ) if not isinstance(_a , torch.Tensor ): __a = self.image_processor(_a , return_tensors='''pt''' ).pixel_values[0].unsqueeze(0 ) __a = image.to(dtype=self.image_encoder.dtype , device=_a ) __a = self.image_encoder(_a )['''last_hidden_state'''] __a = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 __a = image_embeds.repeat_interleave(_a , dim=0 ) if do_classifier_free_guidance: __a = torch.zeros_like(_a ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __a = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(_a ) def __call__( self , _a , _a = 1 , _a = 25 , _a = None , _a = None , _a = 4.0 , _a = 64 , _a = "pil" , _a = True , ): if isinstance(_a , PIL.Image.Image ): __a = 1 elif isinstance(_a , torch.Tensor ): __a = image.shape[0] elif isinstance(_a , _a ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): __a = len(_a ) else: raise ValueError( f'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_a )}''' ) __a = self._execution_device __a = batch_size * num_images_per_prompt __a = guidance_scale > 1.0 __a = self._encode_image(_a , _a , _a , _a ) # prior self.scheduler.set_timesteps(_a , device=_a ) __a = self.scheduler.timesteps __a = self.prior.config.num_embeddings __a = self.prior.config.embedding_dim __a = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , _a , _a , _a , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim __a = latents.reshape(latents.shape[0] , _a , _a ) for i, t in enumerate(self.progress_bar(_a ) ): # expand the latents if we are doing classifier free guidance __a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __a = self.scheduler.scale_model_input(_a , _a ) __a = self.prior( _a , timestep=_a , proj_embedding=_a , ).predicted_image_embedding # remove the variance __a , __a = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: __a , __a = noise_pred.chunk(2 ) __a = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) __a = self.scheduler.step( _a , timestep=_a , sample=_a , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=_a ) __a = [] for i, latent in enumerate(_a ): print() __a = self.renderer.decode( latent[None, :] , _a , size=_a , ray_batch_size=4_096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(_a ) __a = torch.stack(_a ) if output_type not in ["np", "pil"]: raise ValueError(f'''Only the output types `pil` and `np` are supported not output_type={output_type}''' ) __a = images.cpu().numpy() if output_type == "pil": __a = [self.numpy_to_pil(_a ) for image in images] # Offload last model to CPU if hasattr(self , '''final_offload_hook''' ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=_a )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=3 , _a=0.6 , _a=None , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = is_training __a = use_labels __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = type_sequence_label_size __a = initializer_range __a = mask_ratio __a = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = ViTMAEModel(config=_a ) model.to(_a ) model.eval() __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = ViTMAEForPreTraining(_a ) model.to(_a ) model.eval() __a = model(_a ) __a = (self.image_size // self.patch_size) ** 2 __a = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images __a = 1 __a = ViTMAEForPreTraining(_a ) model.to(_a ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(_a ) __a = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[Any] = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () __UpperCAmelCase : str = {'feature-extraction': ViTMAEModel} if is_torch_available() else {} __UpperCAmelCase : List[str] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : int = False __UpperCAmelCase : Any = False def __UpperCAmelCase ( self ): __a = ViTMAEModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMAE does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def __UpperCAmelCase ( self ): __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 ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_a ) def __UpperCAmelCase ( self , _a , _a , _a ): # make masks reproducible np.random.seed(2 ) __a = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) __a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __a = torch.from_numpy(_a ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __a = pt_noise super().check_pt_tf_models(_a , _a , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) model.to(_a ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs[0].cpu().numpy() __a = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a ) __a = model_class.from_pretrained(_a ) model.to(_a ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) # Make sure we don't have nans __a = after_outputs[0].cpu().numpy() __a = 0 __a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_a , 1E-5 ) @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTMAEModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> Optional[int]: __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base''' ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) __a = ViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base''' ).to(_a ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) __a = ViTMAEConfig() __a = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) __a = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): __a = model(**_a , noise=torch.from_numpy(_a ).to(device=_a ) ) # verify the logits __a = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(_a ) , atol=1E-4 ) )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = KandinskyVaaInpaintPipeline __UpperCAmelCase : List[Any] = ['image_embeds', 'negative_image_embeds', 'image', 'mask_image'] __UpperCAmelCase : Dict = [ 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] __UpperCAmelCase : List[str] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] __UpperCAmelCase : Dict = False @property def __UpperCAmelCase ( self ): return 32 @property def __UpperCAmelCase ( self ): return 32 @property def __UpperCAmelCase ( self ): return self.time_input_dim @property def __UpperCAmelCase ( self ): return self.time_input_dim * 4 @property def __UpperCAmelCase ( self ): return 100 @property def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = { '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } __a = UNetaDConditionModel(**_a ) return model @property def __UpperCAmelCase ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = VQModel(**self.dummy_movq_kwargs ) return model def __UpperCAmelCase ( self ): __a = self.dummy_unet __a = self.dummy_movq __a = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule='''linear''' , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=_a , set_alpha_to_one=_a , steps_offset=1 , prediction_type='''epsilon''' , thresholding=_a , ) __a = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __UpperCAmelCase ( self , _a , _a=0 ): __a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_a ) ).to(_a ) __a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _a ) # create init_image __a = floats_tensor((1, 3, 64, 64) , rng=random.Random(_a ) ).to(_a ) __a = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a = Image.fromarray(np.uinta(_a ) ).convert('''RGB''' ).resize((256, 256) ) # create mask __a = np.ones((64, 64) , dtype=np.floataa ) __a = 0 if str(_a ).startswith('''mps''' ): __a = torch.manual_seed(_a ) else: __a = torch.Generator(device=_a ).manual_seed(_a ) __a = { '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def __UpperCAmelCase ( self ): __a = '''cpu''' __a = self.get_dummy_components() __a = self.pipeline_class(**_a ) __a = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = pipe(**self.get_dummy_inputs(_a ) ) __a = output.images __a = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] __a = image[0, -3:, -3:, -1] __a = image_from_tuple[0, -3:, -3:, -1] print(f'''image.shape {image.shape}''' ) assert image.shape == (1, 64, 64, 3) __a = np.array( [0.5077_5903, 0.4952_7195, 0.4882_4543, 0.5019_2237, 0.4864_4906, 0.4937_3814, 0.478_0598, 0.4723_4827, 0.4832_7848] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' def __UpperCAmelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): __a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy''' ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) __a = np.ones((768, 768) , dtype=np.floataa ) __a = 0 __a = '''a hat''' __a = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_a ) __a = KandinskyVaaInpaintPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder-inpaint''' , torch_dtype=torch.floataa ) __a = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) __a = torch.Generator(device='''cpu''' ).manual_seed(0 ) __a , __a = pipe_prior( _a , generator=_a , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() __a = pipeline( image=_a , mask_image=_a , image_embeds=_a , negative_image_embeds=_a , generator=_a , num_inference_steps=100 , height=768 , width=768 , output_type='''np''' , ) __a = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_a , _a )
45
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowercase_ = "platform" import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict=None , lowerCAmelCase__ : str=None , lowerCAmelCase__ : Tuple=None , lowerCAmelCase__ : Optional[int]=None , lowerCAmelCase__ : List[str]=None , lowerCAmelCase__ : List[str]=None , ) -> Optional[int]: if attention_mask is None: __a = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __a = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __a = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=16 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=32 , _a=2 , _a=1 , _a=0 , _a=0.02 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = eos_token_id __a = pad_token_id __a = bos_token_id __a = initializer_range def __UpperCAmelCase ( self ): __a = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) __a = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) __a = shift_tokens_right(_a , 1 , 2 ) __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=_a , ) __a = prepare_blenderbot_inputs_dict(_a , _a , _a ) return config, inputs_dict def __UpperCAmelCase ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a ): __a = 20 __a = model_class_name(_a ) __a = model.encode(inputs_dict['''input_ids'''] ) __a , __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) __a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __a = model.decode( decoder_input_ids[:, -1:] , _a , decoder_attention_mask=_a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_a , ) __a = model.decode(_a , _a ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = 20 __a = model_class_name(_a ) __a = model.encode(inputs_dict['''input_ids'''] ) __a , __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __a = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __a = model.decode( decoder_input_ids[:, -1:] , _a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_a , decoder_position_ids=_a , ) __a = model.decode(_a , _a , decoder_attention_mask=_a ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = 9_9 def __UpperCAmelCase ( self ): __a = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) __a = input_ids.shape[0] __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def __UpperCAmelCase ( self ): __a , __a , __a = self._get_config_and_data() __a = FlaxBlenderbotForConditionalGeneration(_a ) __a = lm_model(input_ids=_a ) __a = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _a ) def __UpperCAmelCase ( self ): __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) __a = FlaxBlenderbotForConditionalGeneration(_a ) __a = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) __a = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) __a = lm_model(input_ids=_a , decoder_input_ids=_a ) __a = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _a ) def __UpperCAmelCase ( self ): __a = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) __a = shift_tokens_right(_a , 1 , 2 ) __a = np.equal(_a , 1 ).astype(np.floataa ).sum() __a = np.equal(_a , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(_a , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : Dict = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) __UpperCAmelCase : List[Any] = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def __UpperCAmelCase ( self ): __a = FlaxBlenderbotModelTester(self ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_a , _a , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_a , _a , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = self._prepare_for_class(_a , _a ) __a = model_class(_a ) @jax.jit def encode_jitted(_a , _a=None , **_a ): return model.encode(input_ids=_a , attention_mask=_a ) with self.subTest('''JIT Enabled''' ): __a = encode_jitted(**_a ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __a = encode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = model_class(_a ) __a = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) __a = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(_a , _a , _a ): return model.decode( decoder_input_ids=_a , decoder_attention_mask=_a , encoder_outputs=_a , ) with self.subTest('''JIT Enabled''' ): __a = decode_jitted(**_a ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __a = decode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __UpperCAmelCase ( self ): for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __a = np.ones((1, 1) ) * model.config.eos_token_id __a = model(_a ) self.assertIsNotNone(_a ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def __UpperCAmelCase ( self ): __a = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 15, '''max_length''': 25} __a = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} __a = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=_a ) __a = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) __a = ['''Sam'''] __a = tokenizer(_a , return_tensors='''jax''' ) __a = model.generate(**_a , **_a ) __a = '''Sam is a great name. It means "sun" in Gaelic.''' __a = tokenizer.batch_decode(_a , **_a ) assert generated_txt[0].strip() == tgt_text
45
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
45
1
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from collections import defaultdict from math import gcd def lowercase ( lowerCAmelCase__ : int = 1500000 ) -> int: __a = defaultdict(lowerCAmelCase__ ) __a = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , lowerCAmelCase__ , 2 ): if gcd(lowerCAmelCase__ , lowerCAmelCase__ ) > 1: continue __a = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(lowerCAmelCase__ , limit + 1 , lowerCAmelCase__ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
1
"""simple docstring""" import random class __lowerCAmelCase : '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = [ord(_a ) for i in text] __a = [] __a = [] for i in plain: __a = random.randint(1 , 300 ) __a = (i + k) * k cipher.append(_a ) key.append(_a ) return cipher, key @staticmethod def __UpperCAmelCase ( _a , _a ): __a = [] for i in range(len(_a ) ): __a = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(_a ) ) return "".join(_a ) if __name__ == "__main__": lowercase_ , lowercase_ = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
1
"""simple docstring""" from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
45
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = self._index.query(_a ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(_a , _a ) if len(_a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_a ) break else: self._duplicate_clusters[close_duplicates[0]].add(_a ) def __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase__ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__ ) ) , max_queue_size=100 ) ): di.add(lowerCAmelCase__ , lowerCAmelCase__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCAmelCase__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCAmelCase__ , lowerCAmelCase__ , ) , total=len(lowerCAmelCase__ ) , ): extremes_list.append(lowerCAmelCase__ ) return extremes_list def lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = dataset.filter(lambda lowerCAmelCase__ , lowerCAmelCase__ : idx not in remove_indices , with_indices=lowerCAmelCase__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = extreme_dict[element['''base_index''']]['''copies'''] print(f'''Original dataset size: {len(lowerCAmelCase__ )}''' ) print(f'''Number of duplicate clusters: {len(lowerCAmelCase__ )}''' ) print(f'''Files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Unique files in duplicate cluster: {len(lowerCAmelCase__ )}''' ) print(f'''Filtered dataset size: {len(lowerCAmelCase__ )}''' ) return ds_filter, duplicate_clusters
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> bool: __a = [int(lowerCAmelCase__ ) for i in ip_va_address.split('''.''' ) if i.isdigit()] return len(lowerCAmelCase__ ) == 4 and all(0 <= int(lowerCAmelCase__ ) <= 254 for octet in octets ) if __name__ == "__main__": lowercase_ = input().strip() lowercase_ = "valid" if is_ip_va_address_valid(ip) else "invalid" print(F'''{ip} is a {valid_or_invalid} IP v4 address.''')
45
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
1
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_xmod": [ "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP", "XmodConfig", "XmodOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "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 lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
1
"""simple docstring""" from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS lowercase_ = logging.get_logger(__name__) lowercase_ = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , _a=None , *_a , **_a ): super().__init__(*_a , **_a ) if config is None: assert isinstance(self.model , _a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f''' {self.model.__class__}''' ) __a = self.model.config else: __a = config __a = data_args __a = self.config.tgt_vocab_size if isinstance(self.config , _a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' ''' padding..''' ) if self.args.label_smoothing == 0: __a = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __a = label_smoothed_nll_loss def __UpperCAmelCase ( self , _a ): if self.optimizer is None: __a = ['''bias''', '''LayerNorm.weight'''] __a = [ { '''params''': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], '''weight_decay''': self.args.weight_decay, }, { '''params''': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], '''weight_decay''': 0.0, }, ] __a = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __a = Adafactor __a = {'''scale_parameter''': False, '''relative_step''': False} else: __a = AdamW __a = { '''betas''': (self.args.adam_betaa, self.args.adam_betaa), '''eps''': self.args.adam_epsilon, } __a = self.args.learning_rate if self.sharded_ddp: __a = OSS( params=_a , optim=_a , **_a , ) else: __a = optimizer_cls(_a , **_a ) if self.lr_scheduler is None: __a = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('''scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.''' ) def __UpperCAmelCase ( self , _a ): __a = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __a = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __a = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __a = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=_a ) return scheduler def __UpperCAmelCase ( self ): if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __UpperCAmelCase ( self , _a , _a , _a ): if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __a = model(**_a , use_cache=_a )[0] __a = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __a , __a = model(**_a , labels=_a , use_cache=_a )[:2] else: # compute label smoothed loss __a = model(**_a , use_cache=_a )[0] __a = torch.nn.functional.log_softmax(_a , dim=-1 ) __a , __a = self.loss_fn(_a , _a , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def __UpperCAmelCase ( self , _a , _a ): __a = inputs.pop('''labels''' ) __a , __a = self._compute_loss(_a , _a , _a ) return loss def __UpperCAmelCase ( self , _a , _a , _a , _a = None , ): __a = self._prepare_inputs(_a ) __a = { '''max_length''': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, '''num_beams''': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __a = self.model.generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , **_a , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __a = self._pad_tensors_to_max_len(_a , gen_kwargs['''max_length'''] ) __a = inputs.pop('''labels''' ) with torch.no_grad(): # compute loss on predict data __a , __a = self._compute_loss(_a , _a , _a ) __a = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __a = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __a = self._pad_tensors_to_max_len(_a , gen_kwargs['''max_length'''] ) return (loss, logits, labels) def __UpperCAmelCase ( self , _a , _a ): # If PAD token is not defined at least EOS token has to be defined __a = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( '''Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be''' f''' padded to `max_length`={max_length}''' ) __a = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __a = tensor return padded_tensor
45
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
1
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class __lowerCAmelCase ( yaml.SafeLoader ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): __a = [self.constructed_objects[key_node] for key_node, _ in node.value] __a = [tuple(_a ) if isinstance(_a , _a ) else key for key in keys] __a = Counter(_a ) __a = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def __UpperCAmelCase ( self , _a , _a=False ): __a = super().construct_mapping(_a , deep=_a ) self._check_no_duplicates_on_constructed_node(_a ) return mapping def lowercase ( lowerCAmelCase__ : str ) -> Tuple[Optional[str], str]: __a = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: __a = full_content[1:].index('''---''' ) + 1 __a = '''\n'''.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(lowerCAmelCase__ ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def __UpperCAmelCase ( cls , _a ): with open(_a , encoding='''utf-8''' ) as readme_file: __a , __a = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(_a ) else: return cls() def __UpperCAmelCase ( self , _a ): if path.exists(): with open(_a , encoding='''utf-8''' ) as readme_file: __a = readme_file.read() else: __a = None __a = self._to_readme(_a ) with open(_a , '''w''' , encoding='''utf-8''' ) as readme_file: readme_file.write(_a ) def __UpperCAmelCase ( self , _a = None ): if readme_content is not None: __a , __a = _split_yaml_from_readme(_a ) __a = '''---\n''' + self.to_yaml_string() + '''---\n''' + content else: __a = '''---\n''' + self.to_yaml_string() + '''---\n''' return full_content @classmethod def __UpperCAmelCase ( cls , _a ): __a = yaml.load(_a , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields __a = { (key.replace('''-''' , '''_''' ) if key.replace('''-''' , '''_''' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**_a ) def __UpperCAmelCase ( self ): return yaml.safe_dump( { (key.replace('''_''' , '''-''' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=_a , allow_unicode=_a , encoding='''utf-8''' , ).decode('''utf-8''' ) lowercase_ = { "image-classification": [], "translation": [], "image-segmentation": [], "fill-mask": [], "automatic-speech-recognition": [], "token-classification": [], "sentence-similarity": [], "audio-classification": [], "question-answering": [], "summarization": [], "zero-shot-classification": [], "table-to-text": [], "feature-extraction": [], "other": [], "multiple-choice": [], "text-classification": [], "text-to-image": [], "text2text-generation": [], "zero-shot-image-classification": [], "tabular-classification": [], "tabular-regression": [], "image-to-image": [], "tabular-to-text": [], "unconditional-image-generation": [], "text-retrieval": [], "text-to-speech": [], "object-detection": [], "audio-to-audio": [], "text-generation": [], "conversational": [], "table-question-answering": [], "visual-question-answering": [], "image-to-text": [], "reinforcement-learning": [], "voice-activity-detection": [], "time-series-forecasting": [], "document-question-answering": [], } if __name__ == "__main__": from argparse import ArgumentParser lowercase_ = ArgumentParser(usage="Validate the yaml metadata block of a README.md file.") ap.add_argument("readme_filepath") lowercase_ = ap.parse_args() lowercase_ = Path(args.readme_filepath) lowercase_ = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
45
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
1
"""simple docstring""" from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): if isinstance(_a , _a ): __a = [label.strip() for label in labels.split(''',''' ) if label.strip()] return labels def __call__( self , _a , _a , _a ): if len(_a ) == 0 or len(_a ) == 0: raise ValueError('''You must include at least one label and at least one sequence.''' ) if hypothesis_template.format(labels[0] ) == hypothesis_template: raise ValueError( ( '''The provided hypothesis_template "{}" was not able to be formatted with the target labels. ''' '''Make sure the passed template includes formatting syntax such as {{}} where the label should go.''' ).format(_a ) ) if isinstance(_a , _a ): __a = [sequences] __a = [] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(_a )] for label in labels] ) return sequence_pairs, sequences @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=ZeroShotClassificationArgumentHandler() , *_a , **_a ): __a = args_parser super().__init__(*_a , **_a ) if self.entailment_id == -1: logger.warning( '''Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to ''' '''-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.''' ) @property def __UpperCAmelCase ( self ): for label, ind in self.model.config.labelaid.items(): if label.lower().startswith('''entail''' ): return ind return -1 def __UpperCAmelCase ( self , _a , _a=True , _a=True , _a=TruncationStrategy.ONLY_FIRST , **_a ): __a = self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( '''Tokenizer was not supporting padding necessary for zero-shot, attempting to use ''' ''' `pad_token=eos_token`''' ) __a = self.tokenizer.eos_token try: __a = self.tokenizer( _a , add_special_tokens=_a , return_tensors=_a , padding=_a , truncation=_a , ) except Exception as e: if "too short" in str(_a ): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. __a = self.tokenizer( _a , add_special_tokens=_a , return_tensors=_a , padding=_a , truncation=TruncationStrategy.DO_NOT_TRUNCATE , ) else: raise e return inputs def __UpperCAmelCase ( self , **_a ): if kwargs.get('''multi_class''' , _a ) is not None: __a = kwargs['''multi_class'''] logger.warning( '''The `multi_class` argument has been deprecated and renamed to `multi_label`. ''' '''`multi_class` will be removed in a future version of Transformers.''' ) __a = {} if "candidate_labels" in kwargs: __a = self._args_parser._parse_labels(kwargs['''candidate_labels'''] ) if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] __a = {} if "multi_label" in kwargs: __a = kwargs['''multi_label'''] return preprocess_params, {}, postprocess_params def __call__( self , _a , *_a , **_a , ): if len(_a ) == 0: pass elif len(_a ) == 1 and "candidate_labels" not in kwargs: __a = args[0] else: raise ValueError(f'''Unable to understand extra arguments {args}''' ) return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , _a , _a=None , _a="This example is {}." ): __a , __a = self._args_parser(_a , _a , _a ) for i, (candidate_label, sequence_pair) in enumerate(zip(_a , _a ) ): __a = self._parse_and_tokenize([sequence_pair] ) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(_a ) - 1, **model_input, } def __UpperCAmelCase ( self , _a ): __a = inputs['''candidate_label'''] __a = inputs['''sequence'''] __a = {k: inputs[k] for k in self.tokenizer.model_input_names} __a = self.model(**_a ) __a = { '''candidate_label''': candidate_label, '''sequence''': sequence, '''is_last''': inputs['''is_last'''], **outputs, } return model_outputs def __UpperCAmelCase ( self , _a , _a=False ): __a = [outputs['''candidate_label'''] for outputs in model_outputs] __a = [outputs['''sequence'''] for outputs in model_outputs] __a = np.concatenate([output['''logits'''].numpy() for output in model_outputs] ) __a = logits.shape[0] __a = len(_a ) __a = N // n __a = logits.reshape((num_sequences, n, -1) ) if multi_label or len(_a ) == 1: # softmax over the entailment vs. contradiction dim for each label independently __a = self.entailment_id __a = -1 if entailment_id == 0 else 0 __a = reshaped_outputs[..., [contradiction_id, entailment_id]] __a = np.exp(_a ) / np.exp(_a ).sum(-1 , keepdims=_a ) __a = scores[..., 1] else: # softmax the "entailment" logits over all candidate labels __a = reshaped_outputs[..., self.entailment_id] __a = np.exp(_a ) / np.exp(_a ).sum(-1 , keepdims=_a ) __a = list(reversed(scores[0].argsort() ) ) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
45
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
1
"""simple docstring""" from __future__ import annotations import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( lowerCAmelCase__ : int ) -> list[int]: __a = str(lowerCAmelCase__ ) __a = [n] for i in range(1 , len(lowerCAmelCase__ ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def lowercase ( lowerCAmelCase__ : int ) -> bool: if len(str(lowerCAmelCase__ ) ) > 3: if not is_prime(int(str(lowerCAmelCase__ )[-3:] ) ) or not is_prime(int(str(lowerCAmelCase__ )[:3] ) ): return False return True def lowercase ( lowerCAmelCase__ : int = 11 ) -> list[int]: __a = [] __a = 13 while len(lowerCAmelCase__ ) != count: if validate(lowerCAmelCase__ ): __a = list_truncated_nums(lowerCAmelCase__ ) if all(is_prime(lowerCAmelCase__ ) for i in list_nums ): list_truncated_primes.append(lowerCAmelCase__ ) num += 2 return list_truncated_primes def lowercase ( ) -> int: return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(F'''{sum(compute_truncated_primes(1_1)) = }''')
45
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
1
"""simple docstring""" import os def lowercase ( ) -> Union[str, Any]: __a = os.path.dirname(os.path.realpath(lowerCAmelCase__ ) ) __a = os.path.join(lowerCAmelCase__ , '''triangle.txt''' ) with open(lowerCAmelCase__ ) as f: __a = f.readlines() __a = [] for line in triangle: __a = [] for number in line.strip().split(''' ''' ): numbers_from_line.append(int(lowerCAmelCase__ ) ) a.append(lowerCAmelCase__ ) for i in range(1 , len(lowerCAmelCase__ ) ): for j in range(len(a[i] ) ): __a = a[i - 1][j] if j != len(a[i - 1] ) else 0 __a = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(lowerCAmelCase__ , lowerCAmelCase__ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *_a , **_a ): warnings.warn( '''The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DPTImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
45
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
1