code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __lowerCAmelCase ( a_ ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = int(number**0.5 ) return number == sq * sq def __lowerCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_ ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den SCREAMING_SNAKE_CASE : Any = x_den * y_den * z_den SCREAMING_SNAKE_CASE : Any = gcd(_UpperCAmelCase , _UpperCAmelCase ) top //= hcf bottom //= hcf return top, bottom def __lowerCAmelCase ( a_ = 35 ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : int = set() SCREAMING_SNAKE_CASE : Dict = 42 SCREAMING_SNAKE_CASE : Optional[Any] = Fraction(0 ) SCREAMING_SNAKE_CASE : str = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 SCREAMING_SNAKE_CASE : Optional[int] = x_num * y_den + x_den * y_num SCREAMING_SNAKE_CASE : List[Any] = x_den * y_den SCREAMING_SNAKE_CASE : Tuple = gcd(_UpperCAmelCase , _UpperCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE : List[str] = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) unique_s.add(_UpperCAmelCase ) # n=2 SCREAMING_SNAKE_CASE : Any = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) SCREAMING_SNAKE_CASE : List[str] = x_den * x_den * y_den * y_den if is_sq(_UpperCAmelCase ) and is_sq(_UpperCAmelCase ): SCREAMING_SNAKE_CASE : Dict = int(sqrt(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE : List[Any] = int(sqrt(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE : List[Any] = gcd(_UpperCAmelCase , _UpperCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE : Union[str, Any] = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) unique_s.add(_UpperCAmelCase ) # n=-1 SCREAMING_SNAKE_CASE : List[Any] = x_num * y_num SCREAMING_SNAKE_CASE : Dict = x_den * y_num + x_num * y_den SCREAMING_SNAKE_CASE : Dict = gcd(_UpperCAmelCase , _UpperCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE : Union[str, Any] = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) unique_s.add(_UpperCAmelCase ) # n=2 SCREAMING_SNAKE_CASE : Tuple = x_num * x_num * y_num * y_num SCREAMING_SNAKE_CASE : Optional[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_UpperCAmelCase ) and is_sq(_UpperCAmelCase ): SCREAMING_SNAKE_CASE : str = int(sqrt(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE : Any = int(sqrt(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE : List[Any] = gcd(_UpperCAmelCase , _UpperCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: SCREAMING_SNAKE_CASE : Union[str, Any] = add_three( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) unique_s.add(_UpperCAmelCase ) for num, den in unique_s: total += Fraction(_UpperCAmelCase , _UpperCAmelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(f"""{solution() = }""")
251
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a , **a) elif isinstance(a , a): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.') return self.tokenizer(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''') if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
0
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( """The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion""" ) __lowerCamelCase = None __lowerCamelCase = { '7B': 1_10_08, '13B': 1_38_24, '30B': 1_79_20, '65B': 2_20_16, '70B': 2_86_72, } __lowerCamelCase = { '7B': 1, '7Bf': 1, '13B': 2, '13Bf': 2, '30B': 4, '65B': 8, '70B': 8, '70Bf': 8, } def UpperCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any]=1 , __lowerCamelCase : Tuple=256 ): return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def UpperCamelCase ( __lowerCamelCase : List[str] ): with open(_UpperCAmelCase , "r" ) as f: return json.load(_UpperCAmelCase ) def UpperCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Tuple ): with open(_UpperCAmelCase , "w" ) as f: json.dump(_UpperCAmelCase , _UpperCAmelCase ) def UpperCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any]=True ): os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase ) snake_case : Tuple = os.path.join(_UpperCAmelCase , "tmp" ) os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase ) snake_case : Tuple = read_json(os.path.join(_UpperCAmelCase , "params.json" ) ) snake_case : Any = NUM_SHARDS[model_size] snake_case : str = params["n_layers"] snake_case : str = params["n_heads"] snake_case : int = n_heads // num_shards snake_case : Union[str, Any] = params["dim"] snake_case : List[Any] = dim // n_heads snake_case : Any = 10000.0 snake_case : Any = 1.0 / (base ** (torch.arange(0 , _UpperCAmelCase , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: snake_case : str = params["n_kv_heads"] # for GQA / MQA snake_case : Optional[Any] = n_heads_per_shard // num_key_value_heads snake_case : List[str] = dim // num_key_value_heads else: # compatibility with other checkpoints snake_case : int = n_heads snake_case : Optional[Any] = n_heads_per_shard snake_case : str = dim # permute for sliced rotary def permute(__lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple=n_heads , __lowerCamelCase : Optional[int]=dim , __lowerCamelCase : Any=dim ): return w.view(_UpperCAmelCase , dima // n_heads // 2 , 2 , _UpperCAmelCase ).transpose(1 , 2 ).reshape(_UpperCAmelCase , _UpperCAmelCase ) print(f"""Fetching all parameters from the checkpoint at {input_base_path}.""" ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) snake_case : Optional[Any] = torch.load(os.path.join(_UpperCAmelCase , "consolidated.00.pth" ) , map_location="cpu" ) else: # Sharded snake_case : Union[str, Any] = [ torch.load(os.path.join(_UpperCAmelCase , f"""consolidated.{i:02d}.pth""" ) , map_location="cpu" ) for i in range(_UpperCAmelCase ) ] snake_case : Dict = 0 snake_case : Optional[int] = {"weight_map": {}} for layer_i in range(_UpperCAmelCase ): snake_case : Tuple = f"""pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded snake_case : Union[str, Any] = { f"""model.layers.{layer_i}.self_attn.q_proj.weight""": permute( loaded[f"""layers.{layer_i}.attention.wq.weight"""] ), f"""model.layers.{layer_i}.self_attn.k_proj.weight""": permute( loaded[f"""layers.{layer_i}.attention.wk.weight"""] ), f"""model.layers.{layer_i}.self_attn.v_proj.weight""": loaded[f"""layers.{layer_i}.attention.wv.weight"""], f"""model.layers.{layer_i}.self_attn.o_proj.weight""": loaded[f"""layers.{layer_i}.attention.wo.weight"""], f"""model.layers.{layer_i}.mlp.gate_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w1.weight"""], f"""model.layers.{layer_i}.mlp.down_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w2.weight"""], f"""model.layers.{layer_i}.mlp.up_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w3.weight"""], f"""model.layers.{layer_i}.input_layernorm.weight""": loaded[f"""layers.{layer_i}.attention_norm.weight"""], f"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[f"""layers.{layer_i}.ffn_norm.weight"""], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. snake_case : Union[str, Any] = { f"""model.layers.{layer_i}.input_layernorm.weight""": loaded[0][ f"""layers.{layer_i}.attention_norm.weight""" ].clone(), f"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[0][ f"""layers.{layer_i}.ffn_norm.weight""" ].clone(), } snake_case : Dict = permute( torch.cat( [ loaded[i][f"""layers.{layer_i}.attention.wq.weight"""].view(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] , dim=0 , ).reshape(_UpperCAmelCase , _UpperCAmelCase ) ) snake_case : Dict = permute( torch.cat( [ loaded[i][f"""layers.{layer_i}.attention.wk.weight"""].view( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] , dim=0 , ).reshape(_UpperCAmelCase , _UpperCAmelCase ) , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) snake_case : int = torch.cat( [ loaded[i][f"""layers.{layer_i}.attention.wv.weight"""].view( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] , dim=0 , ).reshape(_UpperCAmelCase , _UpperCAmelCase ) snake_case : List[str] = torch.cat( [loaded[i][f"""layers.{layer_i}.attention.wo.weight"""] for i in range(_UpperCAmelCase )] , dim=1 ) snake_case : Dict = torch.cat( [loaded[i][f"""layers.{layer_i}.feed_forward.w1.weight"""] for i in range(_UpperCAmelCase )] , dim=0 ) snake_case : Dict = torch.cat( [loaded[i][f"""layers.{layer_i}.feed_forward.w2.weight"""] for i in range(_UpperCAmelCase )] , dim=1 ) snake_case : str = torch.cat( [loaded[i][f"""layers.{layer_i}.feed_forward.w3.weight"""] for i in range(_UpperCAmelCase )] , dim=0 ) snake_case : Union[str, Any] = inv_freq for k, v in state_dict.items(): snake_case : Any = filename param_count += v.numel() torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase ) ) snake_case : Dict = f"""pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded snake_case : Tuple = { "model.embed_tokens.weight": loaded["tok_embeddings.weight"], "model.norm.weight": loaded["norm.weight"], "lm_head.weight": loaded["output.weight"], } else: snake_case : int = { "model.norm.weight": loaded[0]["norm.weight"], "model.embed_tokens.weight": torch.cat( [loaded[i]["tok_embeddings.weight"] for i in range(_UpperCAmelCase )] , dim=1 ), "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(_UpperCAmelCase )] , dim=0 ), } for k, v in state_dict.items(): snake_case : Union[str, Any] = filename param_count += v.numel() torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase ) ) # Write configs snake_case : str = {"total_size": param_count * 2} write_json(_UpperCAmelCase , os.path.join(_UpperCAmelCase , "pytorch_model.bin.index.json" ) ) snake_case : Optional[int] = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1 snake_case : Optional[Any] = params["multiple_of"] if "multiple_of" in params else 256 snake_case : List[Any] = LlamaConfig( hidden_size=_UpperCAmelCase , intermediate_size=compute_intermediate_size(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) , num_attention_heads=params["n_heads"] , num_hidden_layers=params["n_layers"] , rms_norm_eps=params["norm_eps"] , num_key_value_heads=_UpperCAmelCase , ) config.save_pretrained(_UpperCAmelCase ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print("Loading the checkpoint in a Llama model." ) snake_case : Any = LlamaForCausalLM.from_pretrained(_UpperCAmelCase , torch_dtype=torch.floataa , low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("Saving in the Transformers format." ) model.save_pretrained(_UpperCAmelCase , safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def UpperCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[Any] ): # Initialize the tokenizer based on the `spm` model snake_case : List[str] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(f"""Saving a {tokenizer_class.__name__} to {tokenizer_path}.""" ) snake_case : Optional[Any] = tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def UpperCamelCase ( ): snake_case : int = argparse.ArgumentParser() parser.add_argument( "--input_dir" , help="Location of LLaMA weights, which contains tokenizer.model and model folders" , ) parser.add_argument( "--model_size" , choices=["7B", "7Bf", "13B", "13Bf", "30B", "65B", "70B", "70Bf", "tokenizer_only"] , ) parser.add_argument( "--output_dir" , help="Location to write HF model and tokenizer" , ) parser.add_argument("--safe_serialization" , type=_UpperCAmelCase , help="Whether or not to save using `safetensors`." ) snake_case : Tuple = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) snake_case : Optional[int] = os.path.join(args.input_dir , "tokenizer.model" ) write_tokenizer(args.output_dir , _UpperCAmelCase ) if __name__ == "__main__": main()
204
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
def lowercase_ ( __snake_case : int = 50 ) -> List[Any]: '''simple docstring''' snake_case__ :Optional[Any] = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(F'''{solution() = }''')
241
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
0
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy UpperCamelCase__ = logging.getLogger(__name__) UpperCamelCase__ = 'pytorch_model.bin' @dataclasses.dataclass class a : UpperCamelCase : str = dataclasses.field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models."""} ) UpperCamelCase : Optional[str] = dataclasses.field( default=A__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co."""} , ) @dataclasses.dataclass class a : UpperCamelCase : str = dataclasses.field(metadata={"""help""": """A csv or a json file containing the training data."""} ) UpperCamelCase : str = dataclasses.field(metadata={"""help""": """A csv or a json file containing the data to predict on."""} ) UpperCamelCase : Optional[str] = dataclasses.field( default=A__ , metadata={"""help""": """A csv or a json file containing the validation data."""} ) UpperCamelCase : Optional[str] = dataclasses.field( default=A__ , metadata={"""help""": """The name of the task to train on."""} , ) UpperCamelCase : Optional[List[str]] = dataclasses.field( default=A__ , metadata={"""help""": """The list of labels for the task."""} ) @dataclasses.dataclass class a : UpperCamelCase : str = dataclasses.field( metadata={"""help""": """The output directory where the model predictions and checkpoints will be written."""} ) UpperCamelCase : Optional[str] = dataclasses.field( default="""accuracy""" , metadata={"""help""": """The evaluation metric used for the task."""} ) UpperCamelCase : Optional[str] = dataclasses.field( default="""no""" , metadata={ """help""": """The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]""" } , ) UpperCamelCase : Optional[int] = dataclasses.field( default=1_0 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={ """help""": """How much the specified evaluation metric must improve to satisfy early stopping conditions.""" } , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=A__ , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the confidence score."""} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=A__ , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the validation performance."""} , ) UpperCamelCase : Optional[bool] = dataclasses.field( default=A__ , metadata={"""help""": """Whether to fine-tune on labeled data after pseudo training."""} , ) UpperCamelCase : Optional[float] = dataclasses.field( default=0.0 , metadata={"""help""": """Confidence threshold for pseudo-labeled data filtering."""} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=1_0_0 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) UpperCamelCase : Optional[int] = dataclasses.field( default=A__ , metadata={"""help""": """Random seed for initialization."""} , ) def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ): UpperCAmelCase__ : List[Any] = datasets.concatenate_datasets([infer_input, infer_output] ,axis=1 ) if args.do_filter_by_confidence: UpperCAmelCase__ : List[str] = dataset.filter(lambda _snake_case : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 UpperCAmelCase__ : Dict = int(eval_result * len(_UpperCAmelCase ) ) print(_UpperCAmelCase ) UpperCAmelCase__ : int = dataset.sort('probability' ,reverse=_UpperCAmelCase ) UpperCAmelCase__ : Optional[Any] = dataset.select(range(_UpperCAmelCase ) ) UpperCAmelCase__ : Any = dataset.remove_columns(['label', 'probability'] ) UpperCAmelCase__ : Optional[int] = dataset.rename_column('prediction' ,'label' ) UpperCAmelCase__ : Union[str, Any] = dataset.map(lambda _snake_case : {"label": idalabel[example["label"]]} ) UpperCAmelCase__ : Tuple = dataset.shuffle(seed=args.seed ) UpperCAmelCase__ : Dict = os.path.join(_UpperCAmelCase ,F'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(_UpperCAmelCase ,index=_UpperCAmelCase ) else: dataset.to_json(_UpperCAmelCase ) def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ,_snake_case ,**_snake_case ): UpperCAmelCase__ : Union[str, Any] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' ,datefmt='%m/%d/%Y %H:%M:%S' ,level=logging.INFO ,) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() UpperCAmelCase__ : Dict = STModelArguments(model_name_or_path=_UpperCAmelCase ) UpperCAmelCase__ : int = STDataArguments(train_file=_UpperCAmelCase ,infer_file=_UpperCAmelCase ) UpperCAmelCase__ : Dict = STTrainingArguments(output_dir=_UpperCAmelCase ) UpperCAmelCase__ : Optional[int] = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(_UpperCAmelCase ).items(): setattr(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for key, value in kwargs.items(): if hasattr(_UpperCAmelCase ,_UpperCAmelCase ): setattr(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # Sanity checks UpperCAmelCase__ : Tuple = {} UpperCAmelCase__ : Dict = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None UpperCAmelCase__ : Optional[int] = args.train_file UpperCAmelCase__ : Optional[Any] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None UpperCAmelCase__ : Optional[int] = args.eval_file for key in data_files: UpperCAmelCase__ : str = data_files[key].split('.' )[-1] assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: UpperCAmelCase__ : Tuple = extension else: assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('Creating the initial data directory for self-training...' ) UpperCAmelCase__ : Any = F'''{args.output_dir}/self-train_iter-{{}}'''.format UpperCAmelCase__ : Optional[int] = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir ,exist_ok=_UpperCAmelCase ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) accelerator.wait_for_everyone() UpperCAmelCase__ : str = None UpperCAmelCase__ : Any = None UpperCAmelCase__ : Optional[int] = 0 UpperCAmelCase__ : Any = False # Show the progress bar UpperCAmelCase__ : Tuple = tqdm(range(args.max_selftrain_iterations ) ,disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 ,int(args.max_selftrain_iterations ) ): UpperCAmelCase__ : Any = data_dir_format(_UpperCAmelCase ) assert os.path.exists(_UpperCAmelCase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 UpperCAmelCase__ : int = os.path.join(_UpperCAmelCase ,'stage-1' ) UpperCAmelCase__ : str = { 'accelerator': accelerator, 'model_name_or_path': args.model_name_or_path, 'cache_dir': args.cache_dir, 'do_train': True, 'train_file': data_files['train'] if iteration == 0 else data_files['train_pseudo'], 'do_eval': True if args.eval_file is not None else False, 'eval_file': data_files['eval'], 'do_predict': True, 'infer_file': data_files['infer'], 'task_name': args.task_name, 'label_list': args.label_list, 'output_dir': current_output_dir, 'eval_metric': args.eval_metric, 'evaluation_strategy': args.evaluation_strategy, 'early_stopping_patience': args.early_stopping_patience, 'early_stopping_threshold': args.early_stopping_threshold, 'seed': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(_UpperCAmelCase ,_UpperCAmelCase ): arguments_dict.update({key: value} ) UpperCAmelCase__ : Tuple = os.path.join(_UpperCAmelCase ,'best-checkpoint' ,_UpperCAmelCase ) if os.path.exists(_UpperCAmelCase ): logger.info( 'Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.' ,_UpperCAmelCase ,_UpperCAmelCase ,) else: logger.info('***** Running self-training: iteration: %d, stage: 1 *****' ,_UpperCAmelCase ) finetune(**_UpperCAmelCase ) accelerator.wait_for_everyone() assert os.path.exists(_UpperCAmelCase ) logger.info('Self-training job completed: iteration: %d, stage: 1.' ,_UpperCAmelCase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data UpperCAmelCase__ : List[Any] = os.path.join(_UpperCAmelCase ,'best-checkpoint' ) UpperCAmelCase__ : Optional[Any] = os.path.join(_UpperCAmelCase ,'stage-2' ) # Update arguments_dict UpperCAmelCase__ : Tuple = model_path UpperCAmelCase__ : int = data_files['train'] UpperCAmelCase__ : Optional[int] = current_output_dir UpperCAmelCase__ : List[str] = os.path.join(_UpperCAmelCase ,'best-checkpoint' ,_UpperCAmelCase ) if os.path.exists(_UpperCAmelCase ): logger.info( 'Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.' ,_UpperCAmelCase ,_UpperCAmelCase ,) else: logger.info('***** Running self-training: iteration: %d, stage: 2 *****' ,_UpperCAmelCase ) finetune(**_UpperCAmelCase ) accelerator.wait_for_everyone() assert os.path.exists(_UpperCAmelCase ) logger.info('Self-training job completed: iteration: %d, stage: 2.' ,_UpperCAmelCase ) UpperCAmelCase__ : Union[str, Any] = iteration UpperCAmelCase__ : int = data_dir_format(iteration + 1 ) UpperCAmelCase__ : Optional[Any] = AutoConfig.from_pretrained(os.path.join(_UpperCAmelCase ,'best-checkpoint' ) ) UpperCAmelCase__ : List[str] = config.idalabel UpperCAmelCase__ : List[str] = os.path.join(_UpperCAmelCase ,'eval_results_best-checkpoint.json' ) UpperCAmelCase__ : List[str] = os.path.join(_UpperCAmelCase ,'test_results_best-checkpoint.json' ) assert os.path.exists(_UpperCAmelCase ) with open(_UpperCAmelCase ,'r' ) as f: UpperCAmelCase__ : Tuple = float(json.load(_UpperCAmelCase )[args.eval_metric] ) UpperCAmelCase__ : Dict = os.path.join(_UpperCAmelCase ,'infer_output_best-checkpoint.csv' ) assert os.path.exists(_UpperCAmelCase ) # Loading the dataset from local csv or json files. UpperCAmelCase__ : List[Any] = load_dataset(args.data_file_extension ,data_files={'data': data_files['infer']} )['data'] UpperCAmelCase__ : Dict = load_dataset('csv' ,data_files={'data': infer_output_file} )['data'] if accelerator.is_main_process: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) shutil.copy(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,F'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(_UpperCAmelCase ): shutil.copy(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,F'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) accelerator.wait_for_everyone() UpperCAmelCase__ : Optional[int] = os.path.join(_UpperCAmelCase ,F'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: UpperCAmelCase__ : Tuple = eval_result if best_iteration is None: UpperCAmelCase__ : List[Any] = new_iteration UpperCAmelCase__ : int = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: UpperCAmelCase__ : Dict = new_iteration UpperCAmelCase__ : int = new_eval_result UpperCAmelCase__ : Dict = 0 else: if new_eval_result == best_eval_result: UpperCAmelCase__ : str = new_iteration UpperCAmelCase__ : Optional[int] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: UpperCAmelCase__ : Union[str, Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('Best iteration: %d' ,_UpperCAmelCase ) logger.info('Best evaluation result: %s = %f' ,args.eval_metric ,_UpperCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_UpperCAmelCase ,F'''eval_results_iter-{iteration}.json''' ) ,os.path.join(_UpperCAmelCase ,'eval_results_best-iteration.json' ) ,) else: # Assume that the last iteration is the best logger.info('Best iteration: %d' ,args.max_selftrain_iterations - 1 ) logger.info('Best evaluation result: %s = %f' ,args.eval_metric ,_UpperCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_UpperCAmelCase ,F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) ,os.path.join(_UpperCAmelCase ,'eval_results_best-iteration.json' ) ,)
110
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
0
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = 10 def _UpperCamelCase ( self ) -> List[Any]: snake_case_ = [1, 2, 3, 4] snake_case_ = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(a , self.block_size , 0 ) , a ) def _UpperCamelCase ( self ) -> List[Any]: snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(a , self.block_size , 0 ) , a ) def _UpperCamelCase ( self ) -> List[str]: snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(a , self.block_size , 0 ) , a ) def _UpperCamelCase ( self ) -> Any: snake_case_ = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' snake_case_ , snake_case_ = process_story(a ) self.assertEqual(a , [] ) def _UpperCamelCase ( self ) -> Union[str, Any]: snake_case_ = '' snake_case_ , snake_case_ = process_story(a ) self.assertEqual(a , [] ) self.assertEqual(a , [] ) def _UpperCamelCase ( self ) -> Tuple: snake_case_ = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) snake_case_ , snake_case_ = process_story(a ) snake_case_ = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(a , a ) snake_case_ = ['It was the best of times.'] self.assertEqual(a , a ) def _UpperCamelCase ( self ) -> int: snake_case_ = torch.tensor([1, 2, 3, 4] ) snake_case_ = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(a , 0 ).numpy() , expected.numpy() ) def _UpperCamelCase ( self ) -> Tuple: snake_case_ = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) snake_case_ = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(a , 23 ).numpy() , expected.numpy() ) def _UpperCamelCase ( self ) -> Tuple: snake_case_ = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) snake_case_ = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(a , 1 ).numpy() , expected.numpy() ) def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = 1_01 snake_case_ = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_01, 5, 6], [1, 1_01, 3, 4, 1_01, 6]] ) snake_case_ = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) snake_case_ = compute_token_type_ids(a , a ) np.testing.assert_array_equal(a , a )
198
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
"""simple docstring""" from __future__ import annotations a_ = [] def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any ): """simple docstring""" for i in range(len(_UpperCAmelCase ) ): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase ) ): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1 ) , range(_UpperCAmelCase , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1 ) , range(_UpperCAmelCase , len(_UpperCAmelCase ) ) ): if board[i][j] == 1: return False return True def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): """simple docstring""" if row >= len(_UpperCAmelCase ): solution.append(_UpperCAmelCase ) printboard(_UpperCAmelCase ) print() return True for i in range(len(_UpperCAmelCase ) ): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): snake_case_ : Optional[int] = 1 solve(_UpperCAmelCase , row + 1 ) snake_case_ : List[Any] = 0 return False def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : int ): """simple docstring""" for i in range(len(_UpperCAmelCase ) ): for j in range(len(_UpperCAmelCase ) ): if board[i][j] == 1: print("""Q""" , end=""" """ ) else: print(""".""" , end=""" """ ) print() # n=int(input("The no. of queens")) a_ = 8 a_ = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('''The total no. of solutions are :''', len(solution))
480
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { 'vocab_file': 'vocab.txt', 'merges_file': 'bpe.codes', } __snake_case = { 'vocab_file': { 'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt', 'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt', }, 'merges_file': { 'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes', 'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes', }, } __snake_case = { 'vinai/phobert-base': 256, 'vinai/phobert-large': 256, } def _lowercase ( SCREAMING_SNAKE_CASE_ : Any ): """simple docstring""" UpperCamelCase = set() UpperCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCamelCase = char UpperCamelCase = set(_UpperCAmelCase ) return pairs class UpperCAmelCase ( A__ ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : str="<s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : str="</s>" , __magic_name__ : Optional[Any]="<s>" , __magic_name__ : str="<unk>" , __magic_name__ : List[Any]="<pad>" , __magic_name__ : str="<mask>" , **__magic_name__ : str , ): """simple docstring""" super().__init__( bos_token=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , **__magic_name__ , ) UpperCamelCase = vocab_file UpperCamelCase = merges_file UpperCamelCase = {} UpperCamelCase = 0 UpperCamelCase = 1 UpperCamelCase = 2 UpperCamelCase = 3 self.add_from_file(__magic_name__ ) UpperCamelCase = {v: k for k, v in self.encoder.items()} with open(__magic_name__ , encoding="""utf-8""" ) as merges_handle: UpperCamelCase = merges_handle.read().split("""\n""" )[:-1] UpperCamelCase = [tuple(merge.split()[:-1] ) for merge in merges] UpperCamelCase = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCamelCase = {} def lowerCamelCase_ ( self : Any , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCamelCase = [self.cls_token_id] UpperCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase_ ( self : Tuple , __magic_name__ : Tuple , __magic_name__ : Union[str, Any] = None , __magic_name__ : List[str] = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) if token_ids_a is None: return [1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1, 1] + ([0] * len(__magic_name__ )) + [1] def lowerCamelCase_ ( self : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] = None ): """simple docstring""" UpperCamelCase = [self.sep_token_id] UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCamelCase_ ( self : Tuple ): """simple docstring""" return len(self.encoder ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase_ ( self : Union[str, Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" if token in self.cache: return self.cache[token] UpperCamelCase = tuple(__magic_name__ ) UpperCamelCase = tuple(list(word[:-1] ) + [word[-1] + """</w>"""] ) UpperCamelCase = get_pairs(__magic_name__ ) if not pairs: return token while True: UpperCamelCase = min(__magic_name__ , key=lambda __magic_name__ : self.bpe_ranks.get(__magic_name__ , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break UpperCamelCase , UpperCamelCase = bigram UpperCamelCase = [] UpperCamelCase = 0 while i < len(__magic_name__ ): try: UpperCamelCase = word.index(__magic_name__ , __magic_name__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCamelCase = j if word[i] == first and i < len(__magic_name__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCamelCase = tuple(__magic_name__ ) UpperCamelCase = new_word if len(__magic_name__ ) == 1: break else: UpperCamelCase = get_pairs(__magic_name__ ) UpperCamelCase = """@@ """.join(__magic_name__ ) UpperCamelCase = word[:-4] UpperCamelCase = word return word def lowerCamelCase_ ( self : int , __magic_name__ : Dict ): """simple docstring""" UpperCamelCase = [] UpperCamelCase = re.findall(R"""\S+\n?""" , __magic_name__ ) for token in words: split_tokens.extend(list(self.bpe(__magic_name__ ).split(""" """ ) ) ) return split_tokens def lowerCamelCase_ ( self : Optional[int] , __magic_name__ : Union[str, Any] ): """simple docstring""" return self.encoder.get(__magic_name__ , self.encoder.get(self.unk_token ) ) def lowerCamelCase_ ( self : Any , __magic_name__ : List[Any] ): """simple docstring""" return self.decoder.get(__magic_name__ , self.unk_token ) def lowerCamelCase_ ( self : str , __magic_name__ : Dict ): """simple docstring""" UpperCamelCase = """ """.join(__magic_name__ ).replace("""@@ """ , """""" ).strip() return out_string def lowerCamelCase_ ( self : int , __magic_name__ : List[Any] , __magic_name__ : int = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase = os.path.join( __magic_name__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase = os.path.join( __magic_name__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ): copyfile(self.vocab_file , __magic_name__ ) if os.path.abspath(self.merges_file ) != os.path.abspath(__magic_name__ ): copyfile(self.merges_file , __magic_name__ ) return out_vocab_file, out_merge_file def lowerCamelCase_ ( self : Union[str, Any] , __magic_name__ : List[Any] ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): try: with open(__magic_name__ , """r""" , encoding="""utf-8""" ) as fd: self.add_from_file(__magic_name__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(F'Incorrect encoding detected in {f}, please rebuild the dataset' ) return UpperCamelCase = f.readlines() for lineTmp in lines: UpperCamelCase = lineTmp.strip() UpperCamelCase = line.rfind(""" """ ) if idx == -1: raise ValueError("""Incorrect dictionary format, expected \'<token> <cnt>\'""" ) UpperCamelCase = line[:idx] UpperCamelCase = len(self.encoder )
386
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device _lowerCamelCase : str = False class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' pass @nightly @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Tuple: '''simple docstring''' A__ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) A__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''') A__ = torch.manual_seed(0) A__ = pipe.dual_guided( prompt='''first prompt''' , image=UpperCAmelCase__ , text_to_image_strength=0.75 , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(UpperCAmelCase__) A__ = VersatileDiffusionPipeline.from_pretrained(UpperCAmelCase__ , torch_dtype=torch.floataa) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) A__ = generator.manual_seed(0) A__ = pipe.dual_guided( prompt='''first prompt''' , image=UpperCAmelCase__ , text_to_image_strength=0.75 , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image).sum() < 1e-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE ( self : int) ->Any: '''simple docstring''' A__ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) A__ = '''cyberpunk 2077''' A__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''') A__ = torch.manual_seed(0) A__ = pipe.dual_guided( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , text_to_image_strength=0.75 , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images A__ = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) A__ = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 A__ = '''A painting of a squirrel eating a burger ''' A__ = torch.manual_seed(0) A__ = pipe.text_to_image( prompt=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''').images A__ = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) A__ = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 A__ = pipe.image_variation(UpperCAmelCase__ , generator=UpperCAmelCase__ , output_type='''numpy''').images A__ = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) A__ = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1
87
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class __snake_case ( A__ ): """simple docstring""" lowerCAmelCase_ : Optional[Any] = '''ctrl''' lowerCAmelCase_ : str = ['''past_key_values'''] lowerCAmelCase_ : Optional[Any] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self :Union[str, Any] , UpperCamelCase__ :List[str]=246_534 , UpperCamelCase__ :Tuple=256 , UpperCamelCase__ :Any=1_280 , UpperCamelCase__ :Dict=8_192 , UpperCamelCase__ :Dict=48 , UpperCamelCase__ :List[str]=16 , UpperCamelCase__ :Dict=0.1 , UpperCamelCase__ :Union[str, Any]=0.1 , UpperCamelCase__ :Optional[Any]=1E-6 , UpperCamelCase__ :Dict=0.02 , UpperCamelCase__ :List[Any]=True , **UpperCamelCase__ :Tuple , ): _a = vocab_size _a = n_positions _a = n_embd _a = n_layer _a = n_head _a = dff _a = resid_pdrop _a = embd_pdrop _a = layer_norm_epsilon _a = initializer_range _a = use_cache super().__init__(**UpperCamelCase__ )
388
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
'''simple docstring''' import unittest from transformers import DonutProcessor UpperCamelCase_ : Any = 'naver-clova-ix/donut-base' class lowerCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase_ ( self : int ): a__ = DonutProcessor.from_pretrained(a__ ) def lowerCAmelCase_ ( self : Union[str, Any] ): a__ = { "name": "John Doe", "age": "99", "city": "Atlanta", "state": "GA", "zip": "30301", "phone": "123-4567", "nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}], } a__ = ( "<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>" "<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>" "<s_nicknames><s_nickname>Johnny</s_nickname>" "<sep/><s_nickname>JD</s_nickname></s_nicknames>" ) a__ = self.processor.tokenajson(a__ ) self.assertDictEqual(a__ ,a__ )
331
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : 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=37 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
0
"""simple docstring""" import numpy as np import datasets __snake_case : str = '\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' __snake_case : str = '\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' __snake_case : Tuple = '\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self: Tuple) -> int: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "X": datasets.Sequence(datasets.Value("float" , id="sequence") , id="X"), }) , ) def _SCREAMING_SNAKE_CASE ( self: int , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> str: """simple docstring""" __lowerCAmelCase : Optional[int] = np.array(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = np.array(_SCREAMING_SNAKE_CASE) # Assert that arrays are 2D if len(X.shape) != 2: raise ValueError("Expected `X` to be a 2D vector") if len(reference_distribution.shape) != 2: raise ValueError("Expected `reference_distribution` to be a 2D vector") if reference_distribution.shape[0] < 2: raise ValueError( "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension") # Get mahalanobis distance for each prediction __lowerCAmelCase : int = X - np.mean(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = np.cov(reference_distribution.T) try: __lowerCAmelCase : int = np.linalg.inv(_SCREAMING_SNAKE_CASE) except np.linalg.LinAlgError: __lowerCAmelCase : Union[str, Any] = np.linalg.pinv(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Any = np.dot(_SCREAMING_SNAKE_CASE , X_minus_mu.T).diagonal() return {"mahalanobis": mahal_dist}
293
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor _lowerCAmelCase :List[Any] = logging.get_logger(__name__) class UpperCAmelCase ( A__ ): '''simple docstring''' def __init__( self , *lowercase__ , **lowercase__ ) -> None: warnings.warn( 'The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use ChineseCLIPImageProcessor instead.' , lowercase__ , ) super().__init__(*lowercase__ , **lowercase__ )
251
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) 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.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker __lowerCamelCase = 'CompVis/stable-diffusion-v1-1' __lowerCamelCase = 'CompVis/stable-diffusion-v1-2' __lowerCamelCase = 'CompVis/stable-diffusion-v1-3' __lowerCamelCase = 'CompVis/stable-diffusion-v1-4' class UpperCAmelCase ( A__ ): def __init__(self : Dict , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Any , snake_case__ : Any , snake_case__ : Optional[int] , snake_case__ : Any , snake_case__ : Tuple , snake_case__ : List[str] = True , ) -> str: '''simple docstring''' super()._init_() snake_case : int = StableDiffusionPipeline.from_pretrained(snake_case__ ) snake_case : List[str] = StableDiffusionPipeline.from_pretrained(snake_case__ ) snake_case : str = StableDiffusionPipeline.from_pretrained(snake_case__ ) snake_case : Optional[Any] = StableDiffusionPipeline( vae=snake_case__ , text_encoder=snake_case__ , tokenizer=snake_case__ , unet=snake_case__ , scheduler=snake_case__ , safety_checker=snake_case__ , feature_extractor=snake_case__ , requires_safety_checker=snake_case__ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def _SCREAMING_SNAKE_CASE (self : Dict ) -> Dict[str, Any]: '''simple docstring''' return {k: getattr(self , snake_case__ ) for k in self.config.keys() if not k.startswith("_" )} def _SCREAMING_SNAKE_CASE (self : List[str] , snake_case__ : Tuple = "auto" ) -> int: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory snake_case : Tuple = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Tuple ) -> Dict: '''simple docstring''' self.enable_attention_slicing(snake_case__ ) @torch.no_grad() def _SCREAMING_SNAKE_CASE (self : int , snake_case__ : Any , snake_case__ : str = 5_12 , snake_case__ : str = 5_12 , snake_case__ : str = 50 , snake_case__ : Optional[Any] = 7.5 , snake_case__ : Any = None , snake_case__ : Union[str, Any] = 1 , snake_case__ : Tuple = 0.0 , snake_case__ : List[str] = None , snake_case__ : Optional[Any] = None , snake_case__ : Any = "pil" , snake_case__ : Optional[Any] = True , snake_case__ : List[Any] = None , snake_case__ : Dict = 1 , **snake_case__ : Optional[int] , ) -> Tuple: '''simple docstring''' return self.pipea( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) @torch.no_grad() def _SCREAMING_SNAKE_CASE (self : Tuple , snake_case__ : List[str] , snake_case__ : Optional[int] = 5_12 , snake_case__ : Tuple = 5_12 , snake_case__ : List[str] = 50 , snake_case__ : List[str] = 7.5 , snake_case__ : int = None , snake_case__ : str = 1 , snake_case__ : Any = 0.0 , snake_case__ : Any = None , snake_case__ : Optional[int] = None , snake_case__ : List[Any] = "pil" , snake_case__ : Union[str, Any] = True , snake_case__ : List[str] = None , snake_case__ : int = 1 , **snake_case__ : Tuple , ) -> Dict: '''simple docstring''' return self.pipea( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) @torch.no_grad() def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : Dict , snake_case__ : List[Any] = 5_12 , snake_case__ : int = 5_12 , snake_case__ : List[Any] = 50 , snake_case__ : Optional[int] = 7.5 , snake_case__ : Tuple = None , snake_case__ : List[Any] = 1 , snake_case__ : int = 0.0 , snake_case__ : Optional[int] = None , snake_case__ : str = None , snake_case__ : Tuple = "pil" , snake_case__ : Optional[int] = True , snake_case__ : Dict = None , snake_case__ : Dict = 1 , **snake_case__ : Union[str, Any] , ) -> List[str]: '''simple docstring''' return self.pipea( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) @torch.no_grad() def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : Any , snake_case__ : Optional[Any] = 5_12 , snake_case__ : Tuple = 5_12 , snake_case__ : Optional[int] = 50 , snake_case__ : str = 7.5 , snake_case__ : Tuple = None , snake_case__ : Any = 1 , snake_case__ : List[Any] = 0.0 , snake_case__ : List[str] = None , snake_case__ : int = None , snake_case__ : str = "pil" , snake_case__ : Optional[Any] = True , snake_case__ : Optional[Any] = None , snake_case__ : List[str] = 1 , **snake_case__ : Optional[Any] , ) -> int: '''simple docstring''' return self.pipea( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) @torch.no_grad() def _SCREAMING_SNAKE_CASE (self : int , snake_case__ : Any , snake_case__ : Optional[int] = 5_12 , snake_case__ : Dict = 5_12 , snake_case__ : Optional[int] = 50 , snake_case__ : Any = 7.5 , snake_case__ : Union[str, Any] = None , snake_case__ : str = 1 , snake_case__ : Tuple = 0.0 , snake_case__ : Any = None , snake_case__ : Optional[int] = None , snake_case__ : Optional[Any] = "pil" , snake_case__ : Optional[int] = True , snake_case__ : str = None , snake_case__ : str = 1 , **snake_case__ : Dict , ) -> Dict: '''simple docstring''' snake_case : Dict = "cuda" if torch.cuda.is_available() else "cpu" self.to(snake_case__ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(f"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" ) # Get first result from Stable Diffusion Checkpoint v1.1 snake_case : Optional[Any] = self.textaimg_sda_a( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) # Get first result from Stable Diffusion Checkpoint v1.2 snake_case : Dict = self.textaimg_sda_a( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) # Get first result from Stable Diffusion Checkpoint v1.3 snake_case : Union[str, Any] = self.textaimg_sda_a( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) # Get first result from Stable Diffusion Checkpoint v1.4 snake_case : str = self.textaimg_sda_a( prompt=snake_case__ , height=snake_case__ , width=snake_case__ , num_inference_steps=snake_case__ , guidance_scale=snake_case__ , negative_prompt=snake_case__ , num_images_per_prompt=snake_case__ , eta=snake_case__ , generator=snake_case__ , latents=snake_case__ , output_type=snake_case__ , return_dict=snake_case__ , callback=snake_case__ , callback_steps=snake_case__ , **snake_case__ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
204
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def lowercase_ ( __snake_case : Tuple ) -> Any: '''simple docstring''' if hor == 1_28: snake_case__ :Dict = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") snake_case__ :Optional[int] = (32, 1_28, 2_56) snake_case__ :List[Any] = ("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: snake_case__ :List[str] = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") snake_case__ :Optional[Any] = (32, 64, 1_28, 2_56) snake_case__ :Union[str, Any] = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") snake_case__ :Optional[int] = torch.load(F'/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch' ) snake_case__ :Optional[int] = model.state_dict() snake_case__ :List[str] = { "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 6_55_36, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } snake_case__ :Tuple = UNetaDModel(**_UpperCAmelCase ) print(F'length of state dict: {len(state_dict.keys() )}' ) print(F'length of value function dict: {len(hf_value_function.state_dict().keys() )}' ) snake_case__ :str = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case__ :Tuple = state_dict.pop(_UpperCAmelCase ) hf_value_function.load_state_dict(_UpperCAmelCase ) torch.save(hf_value_function.state_dict() , F'hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin' ) with open(F'hub/hopper-medium-v2/unet/hor{hor}/config.json' , "w" ) as f: json.dump(_UpperCAmelCase , _UpperCAmelCase ) def lowercase_ ( ) -> List[Any]: '''simple docstring''' snake_case__ :List[str] = { "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 1_28, 2_56), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 6_55_36, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } snake_case__ :Tuple = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) snake_case__ :Dict = model snake_case__ :Optional[int] = UNetaDModel(**_UpperCAmelCase ) print(F'length of state dict: {len(state_dict.keys() )}' ) print(F'length of value function dict: {len(hf_value_function.state_dict().keys() )}' ) snake_case__ :List[Any] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case__ :Dict = state_dict.pop(_UpperCAmelCase ) hf_value_function.load_state_dict(_UpperCAmelCase ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": unet(3_2) # unet(128) value_function()
241
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
"""simple docstring""" import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCamelCase ( *_snake_case ,_snake_case = None ,_snake_case=True ,_snake_case=2 ): from .. import __version__ UpperCAmelCase__ : Optional[int] = take_from UpperCAmelCase__ : Tuple = () if not isinstance(args[0] ,_UpperCAmelCase ): UpperCAmelCase__ : List[Any] = (args,) for attribute, version_name, message in args: if version.parse(version.parse(_UpperCAmelCase ).base_version ) >= version.parse(_UpperCAmelCase ): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''' ) UpperCAmelCase__ : Any = None if isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(_UpperCAmelCase ),) UpperCAmelCase__ : List[str] = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(_UpperCAmelCase ,_UpperCAmelCase ): values += (getattr(_UpperCAmelCase ,_UpperCAmelCase ),) UpperCAmelCase__ : List[str] = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: UpperCAmelCase__ : Union[str, Any] = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: UpperCAmelCase__ : Optional[int] = warning + ' ' if standard_warn else '' warnings.warn(warning + message ,_UpperCAmelCase ,stacklevel=_UpperCAmelCase ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and len(_UpperCAmelCase ) > 0: UpperCAmelCase__ : Any = inspect.getouterframes(inspect.currentframe() )[1] UpperCAmelCase__ : Union[str, Any] = call_frame.filename UpperCAmelCase__ : int = call_frame.lineno UpperCAmelCase__ : Union[str, Any] = call_frame.function UpperCAmelCase__ , UpperCAmelCase__ : int = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(_UpperCAmelCase ) == 0: return elif len(_UpperCAmelCase ) == 1: return values[0] return values
110
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging lowercase = '\\n\n' lowercase = '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n' lowercase = '\nArgs:\n model_id (str): model used for calculating Perplexity\n NOTE: Perplexity can only be calculated for causal language models.\n This includes models such as gpt2, causal variations of bert,\n causal versions of t5, and more (the full list can be found\n in the AutoModelForCausalLM documentation here:\n https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n input_texts (list of str): input text, each separate text snippet\n is one list entry.\n batch_size (int): the batch size to run texts through the model. Defaults to 16.\n add_start_token (bool): whether to add the start token to the texts,\n so the perplexity can include the probability of the first word. Defaults to True.\n device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n perplexity: dictionary containing the perplexity scores for the texts\n in the input list, as well as the mean perplexity. If one of the input texts is\n longer than the max input length of the model, then it is truncated to the\n max length for the perplexity computation.\nExamples:\n Example 1:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... add_start_token=False,\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 78.22\n >>> print(round(results["perplexities"][0], 2))\n 11.11\n\n Example 2:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = datasets.load_dataset("wikitext",\n ... "wikitext-2-raw-v1",\n ... split="test")["text"][:50] # doctest:+ELLIPSIS\n [...]\n >>> input_texts = [s for s in input_texts if s!=\'\']\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 60.35\n >>> print(round(results["perplexities"][0], 2))\n 81.12\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): '''simple docstring''' def _UpperCamelCase ( self ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'input_texts': datasets.Value('string' ), } ) , reference_urls=['https://huggingface.co/docs/transformers/perplexity'] , ) def _UpperCamelCase ( self , a , a , a = 16 , a = True , a=None ) -> List[Any]: if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": snake_case_ = 'cuda' else: snake_case_ = 'cuda' if torch.cuda.is_available() else 'cpu' snake_case_ = AutoModelForCausalLM.from_pretrained(a ) snake_case_ = model.to(a ) snake_case_ = AutoTokenizer.from_pretrained(a ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: snake_case_ = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(a ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'pad_token': existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" snake_case_ = model.config.max_length - 1 else: snake_case_ = model.config.max_length snake_case_ = tokenizer( a , add_special_tokens=a , padding=a , truncation=a , max_length=a , return_tensors='pt' , return_attention_mask=a , ).to(a ) snake_case_ = encodings['input_ids'] snake_case_ = encodings['attention_mask'] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." snake_case_ = [] snake_case_ = CrossEntropyLoss(reduction='none' ) for start_index in logging.tqdm(range(0 , len(a ) , a ) ): snake_case_ = min(start_index + batch_size , len(a ) ) snake_case_ = encoded_texts[start_index:end_index] snake_case_ = attn_masks[start_index:end_index] if add_start_token: snake_case_ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(a ) snake_case_ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) snake_case_ = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(a ), attn_mask] , dim=1 ) snake_case_ = encoded_batch with torch.no_grad(): snake_case_ = model(a , attention_mask=a ).logits snake_case_ = out_logits[..., :-1, :].contiguous() snake_case_ = labels[..., 1:].contiguous() snake_case_ = attn_mask[..., 1:].contiguous() snake_case_ = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , a ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(a )}
198
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
"""simple docstring""" import copy 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 from ..auto import CONFIG_MAPPING a_ = logging.get_logger(__name__) a_ = { 'microsoft/conditional-detr-resnet-50': ( 'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json' ), } class __lowercase ( A__): """simple docstring""" _A : List[str] = '''conditional_detr''' _A : Optional[Any] = ['''past_key_values'''] _A : Optional[Any] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__(self , lowercase__=True , lowercase__=None , lowercase__=3 , lowercase__=3_00 , lowercase__=6 , lowercase__=20_48 , lowercase__=8 , lowercase__=6 , lowercase__=20_48 , lowercase__=8 , lowercase__=0.0 , lowercase__=0.0 , lowercase__=True , lowercase__="relu" , lowercase__=2_56 , lowercase__=0.1 , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1.0 , lowercase__=False , lowercase__="sine" , lowercase__="resnet50" , lowercase__=True , lowercase__=False , lowercase__=2 , lowercase__=5 , lowercase__=2 , lowercase__=1 , lowercase__=1 , lowercase__=2 , lowercase__=5 , lowercase__=2 , lowercase__=0.25 , **lowercase__ , ): if backbone_config is not None and use_timm_backbone: raise ValueError("""You can\'t specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) snake_case_ : List[Any] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowercase__ , lowercase__ ): snake_case_ : Any = backbone_config.get("""model_type""" ) snake_case_ : Dict = CONFIG_MAPPING[backbone_model_type] snake_case_ : Tuple = config_class.from_dict(lowercase__ ) snake_case_ : Optional[int] = use_timm_backbone snake_case_ : List[Any] = backbone_config snake_case_ : List[Any] = num_channels snake_case_ : int = num_queries snake_case_ : int = d_model snake_case_ : Union[str, Any] = encoder_ffn_dim snake_case_ : Optional[int] = encoder_layers snake_case_ : Optional[int] = encoder_attention_heads snake_case_ : List[str] = decoder_ffn_dim snake_case_ : str = decoder_layers snake_case_ : Dict = decoder_attention_heads snake_case_ : List[Any] = dropout snake_case_ : Dict = attention_dropout snake_case_ : Dict = activation_dropout snake_case_ : str = activation_function snake_case_ : List[str] = init_std snake_case_ : Optional[Any] = init_xavier_std snake_case_ : List[str] = encoder_layerdrop snake_case_ : List[str] = decoder_layerdrop snake_case_ : Any = encoder_layers snake_case_ : str = auxiliary_loss snake_case_ : List[Any] = position_embedding_type snake_case_ : Union[str, Any] = backbone snake_case_ : Optional[Any] = use_pretrained_backbone snake_case_ : Any = dilation # Hungarian matcher snake_case_ : List[str] = class_cost snake_case_ : Optional[Any] = bbox_cost snake_case_ : List[Any] = giou_cost # Loss coefficients snake_case_ : Optional[int] = mask_loss_coefficient snake_case_ : List[str] = dice_loss_coefficient snake_case_ : Optional[Any] = cls_loss_coefficient snake_case_ : Dict = bbox_loss_coefficient snake_case_ : Optional[Any] = giou_loss_coefficient snake_case_ : Tuple = focal_alpha super().__init__(is_encoder_decoder=lowercase__ , **lowercase__ ) @property def __UpperCamelCase (self ): return self.encoder_attention_heads @property def __UpperCamelCase (self ): return self.d_model def __UpperCamelCase (self ): snake_case_ : List[str] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: snake_case_ : int = self.backbone_config.to_dict() snake_case_ : Dict = self.__class__.model_type return output class __lowercase ( A__): """simple docstring""" _A : int = version.parse("""1.11""") @property def __UpperCamelCase (self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def __UpperCamelCase (self ): return 1e-5 @property def __UpperCamelCase (self ): return 12
480
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = [[1, 2, 4], [1, 2, 3, 4]] UpperCamelCase = DisjunctiveConstraint(__magic_name__ ) self.assertTrue(isinstance(dc.token_ids , __magic_name__ ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(__magic_name__ ) # fails here def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = [[1, 2, 3], [1, 2, 4]] UpperCamelCase = DisjunctiveConstraint(__magic_name__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(1 ) UpperCamelCase = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(2 ) UpperCamelCase = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(3 ) UpperCamelCase = stepped is True and completed is True and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] UpperCamelCase = DisjunctiveConstraint(__magic_name__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCamelCase , UpperCamelCase , UpperCamelCase = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
386
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
0
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, 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 _lowerCamelCase : Dict = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class UpperCamelCase_ : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any]=16 , UpperCAmelCase__ : Tuple=13 , UpperCAmelCase__ : List[str]=7 , UpperCAmelCase__ : str=14 , UpperCAmelCase__ : List[Any]=10 , UpperCAmelCase__ : List[str]=19 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[Any]=16 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Optional[Any]=[1, 2, 3, 4, 5] , UpperCAmelCase__ : Union[str, Any]=25 , UpperCAmelCase__ : Any=5 , ) ->Optional[int]: '''simple docstring''' A__ = d_model A__ = parent A__ = batch_size A__ = prediction_length A__ = context_length A__ = cardinality A__ = num_time_features A__ = lags_sequence A__ = embedding_dimension A__ = is_training 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__ = context_length A__ = prediction_length + label_length A__ = label_length A__ = moving_average A__ = autocorrelation_factor def SCREAMING_SNAKE_CASE ( self : str) ->Dict: '''simple docstring''' return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : Union[str, Any]) ->Dict: '''simple docstring''' A__ = config.context_length + max(config.lags_sequence) A__ = ids_tensor([self.batch_size, 1] , config.cardinality[0]) A__ = floats_tensor([self.batch_size, _past_length, config.num_time_features]) A__ = floats_tensor([self.batch_size, _past_length]) A__ = floats_tensor([self.batch_size, _past_length]) > 0.5 # decoder inputs A__ = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]) A__ = floats_tensor([self.batch_size, config.prediction_length]) A__ = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' A__ = self.get_config() A__ = self.prepare_autoformer_inputs_dict(UpperCAmelCase__) return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->int: '''simple docstring''' A__ , A__ = self.prepare_config_and_inputs() return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict) ->Tuple: '''simple docstring''' A__ = AutoformerModel(config=UpperCAmelCase__).to(UpperCAmelCase__).eval() A__ = model(**UpperCAmelCase__) A__ = outputs.encoder_last_hidden_state A__ = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: A__ = model.get_encoder() encoder.save_pretrained(UpperCAmelCase__) A__ = AutoformerEncoder.from_pretrained(UpperCAmelCase__).to(UpperCAmelCase__) A__ , A__ , A__ , A__ , A__ = model.create_network_inputs(**UpperCAmelCase__) A__ , A__ = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]) A__ = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) A__ = encoder(inputs_embeds=UpperCAmelCase__)[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3) A__ = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1) .unsqueeze(1) .repeat(1 , config.prediction_length , 1) ) A__ = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) A__ = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) A__ = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: A__ = model.get_decoder() decoder.save_pretrained(UpperCAmelCase__) A__ = AutoformerDecoder.from_pretrained(UpperCAmelCase__).to(UpperCAmelCase__) A__ = decoder( trend=UpperCAmelCase__ , inputs_embeds=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3) @require_torch class UpperCamelCase_ ( A__ , A__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () UpperCAmelCase__ = (AutoformerForPrediction,) if is_torch_available() else () UpperCAmelCase__ = {'''feature-extraction''': AutoformerModel} if is_torch_available() else {} UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' A__ = AutoformerModelTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Any) ->Tuple: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: A__ = model_class(UpperCAmelCase__) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCAmelCase__) A__ , A__ = model_class.from_pretrained(UpperCAmelCase__ , output_loading_info=UpperCAmelCase__) self.assertEqual(info['''missing_keys'''] , []) def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*UpperCAmelCase__) @unittest.skip(reason='''Model has no tokens embeddings''') def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->int: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Optional[Any]: '''simple docstring''' A__ = inspect.signature(getattr(UpperCAmelCase__ , '''forward''')) # The main input is the name of the argument after `self` A__ = list(model_signature.parameters.keys())[1] self.assertEqual(AutoformerModel.main_input_name , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Dict: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(UpperCAmelCase__) A__ = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ = [*signature.parameters.keys()] A__ = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''') expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ]) self.assertListEqual(arg_names[: len(UpperCAmelCase__)] , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Tuple: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = True A__ = getattr(self.model_tester , '''seq_length''' , UpperCAmelCase__) A__ = getattr(self.model_tester , '''decoder_seq_length''' , UpperCAmelCase__) A__ = getattr(self.model_tester , '''encoder_seq_length''' , UpperCAmelCase__) A__ = getattr(self.model_tester , '''d_model''' , UpperCAmelCase__) A__ = getattr(self.model_tester , '''num_attention_heads''' , UpperCAmelCase__) A__ = d_model // num_attention_heads for model_class in self.all_model_classes: A__ = True A__ = False A__ = True A__ = model_class(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__)) A__ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(UpperCAmelCase__) , self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] A__ = True A__ = model_class(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__)) A__ = outputs.encoder_attentions self.assertEqual(len(UpperCAmelCase__) , self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) A__ = len(UpperCAmelCase__) A__ = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) # decoder attentions A__ = outputs.decoder_attentions self.assertIsInstance(UpperCAmelCase__ , (list, tuple)) self.assertEqual(len(UpperCAmelCase__) , self.model_tester.num_hidden_layers) self.assertListEqual( list(decoder_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions A__ = outputs.cross_attentions self.assertIsInstance(UpperCAmelCase__ , (list, tuple)) self.assertEqual(len(UpperCAmelCase__) , self.model_tester.num_hidden_layers) self.assertListEqual( list(cross_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine A__ = True A__ = True A__ = model_class(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__)) self.assertEqual(out_len + 2 , len(UpperCAmelCase__)) A__ = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(UpperCAmelCase__) , self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[int]: '''simple docstring''' super().test_retain_grad_hidden_states_attentions() def SCREAMING_SNAKE_CASE ( lowercase_="train-batch.pt" ) -> Dict: """simple docstring""" A__ = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=_UpperCAmelCase , repo_type='''dataset''' ) A__ = torch.load(_UpperCAmelCase , map_location=_UpperCAmelCase ) return batch @require_torch @slow class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[Any]: '''simple docstring''' A__ = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''').to(UpperCAmelCase__) A__ = prepare_batch() with torch.no_grad(): A__ = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] A__ = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size)) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=UpperCAmelCase__) self.assertTrue(torch.allclose(output[0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Optional[int]: '''simple docstring''' A__ = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''').to(UpperCAmelCase__) A__ = prepare_batch('''val-batch.pt''') with torch.no_grad(): A__ = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state A__ = torch.Size((64, model.config.context_length, model.config.d_model)) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=UpperCAmelCase__) self.assertTrue(torch.allclose(output[0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Union[str, Any]: '''simple docstring''' A__ = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''').to(UpperCAmelCase__) A__ = prepare_batch('''val-batch.pt''') with torch.no_grad(): A__ = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) A__ = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length)) self.assertEqual(outputs.sequences.shape , UpperCAmelCase__) A__ = torch.tensor([3_130.6_763, 4_056.5_293, 7_053.0_786] , device=UpperCAmelCase__) A__ = outputs.sequences.mean(dim=1) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , UpperCAmelCase__ , rtol=1e-1))
87
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
"""simple docstring""" # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def __a ( a ): """simple docstring""" _a = [False] * len(_UpperCAmelCase ) _a = [-1] * len(_UpperCAmelCase ) def dfs(a, a ): _a = True _a = c for u in graph[v]: if not visited[u]: dfs(_UpperCAmelCase, 1 - c ) for i in range(len(_UpperCAmelCase ) ): if not visited[i]: dfs(_UpperCAmelCase, 0 ) for i in range(len(_UpperCAmelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph __SCREAMING_SNAKE_CASE = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
388
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
0
'''simple docstring''' import json import sys def _lowerCAmelCase (_lowercase , _lowercase ): """simple docstring""" with open(_UpperCAmelCase , encoding="utf-8" ) as f: a__ = json.load(_UpperCAmelCase ) a__ = ["<details>", "<summary>Show updated benchmarks!</summary>", " "] for benchmark_name in sorted(_UpperCAmelCase ): a__ = results[benchmark_name] a__ = benchmark_name.split("/" )[-1] output_md.append(F'### Benchmark: {benchmark_file_name}' ) a__ = "| metric |" a__ = "|--------|" a__ = "| new / old (diff) |" for metric_name in sorted(_UpperCAmelCase ): a__ = benchmark_res[metric_name] a__ = metric_vals["new"] a__ = metric_vals.get("old" , _UpperCAmelCase ) a__ = metric_vals.get("diff" , _UpperCAmelCase ) a__ = F' {new_val:f}' if isinstance(_UpperCAmelCase , (int, float) ) else "None" if old_val is not None: val_str += F' / {old_val:f}' if isinstance(_UpperCAmelCase , (int, float) ) else "None" if dif_val is not None: val_str += F' ({dif_val:f})' if isinstance(_UpperCAmelCase , (int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append("</details>" ) with open(_UpperCAmelCase , "w" , encoding="utf-8" ) as f: f.writelines("\n".join(_UpperCAmelCase ) ) if __name__ == "__main__": UpperCamelCase_ : Dict = sys.argv[1] UpperCamelCase_ : List[str] = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
331
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" import inspect import unittest from transformers import ConvNextConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : '''simple docstring''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Optional[int]=13 , _SCREAMING_SNAKE_CASE: int=32 , _SCREAMING_SNAKE_CASE: Union[str, Any]=3 , _SCREAMING_SNAKE_CASE: Optional[Any]=4 , _SCREAMING_SNAKE_CASE: int=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE: Any=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE: Any=True , _SCREAMING_SNAKE_CASE: Dict=True , _SCREAMING_SNAKE_CASE: Optional[int]=37 , _SCREAMING_SNAKE_CASE: Union[str, Any]="gelu" , _SCREAMING_SNAKE_CASE: Tuple=10 , _SCREAMING_SNAKE_CASE: Optional[Any]=0.02 , _SCREAMING_SNAKE_CASE: int=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE: int=[2, 3, 4] , _SCREAMING_SNAKE_CASE: Any=None , ) -> str: """simple docstring""" __lowerCAmelCase : Tuple = parent __lowerCAmelCase : List[Any] = batch_size __lowerCAmelCase : Union[str, Any] = image_size __lowerCAmelCase : str = num_channels __lowerCAmelCase : Tuple = num_stages __lowerCAmelCase : List[str] = hidden_sizes __lowerCAmelCase : List[Any] = depths __lowerCAmelCase : List[Any] = is_training __lowerCAmelCase : Union[str, Any] = use_labels __lowerCAmelCase : Optional[int] = intermediate_size __lowerCAmelCase : List[Any] = hidden_act __lowerCAmelCase : str = num_labels __lowerCAmelCase : Optional[Any] = initializer_range __lowerCAmelCase : Dict = out_features __lowerCAmelCase : int = out_indices __lowerCAmelCase : List[Any] = scope def _SCREAMING_SNAKE_CASE ( self: str) -> Dict: """simple docstring""" __lowerCAmelCase : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCAmelCase : Dict = None if self.use_labels: __lowerCAmelCase : int = ids_tensor([self.batch_size] , self.num_labels) __lowerCAmelCase : Dict = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self: str) -> str: """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def _SCREAMING_SNAKE_CASE ( self: Dict , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: str) -> int: """simple docstring""" __lowerCAmelCase : List[Any] = ConvNextModel(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _SCREAMING_SNAKE_CASE ( self: str , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[Any]) -> Any: """simple docstring""" __lowerCAmelCase : Any = ConvNextForImageClassification(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : str = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> Dict: """simple docstring""" __lowerCAmelCase : Dict = ConvNextBackbone(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : Tuple = model(_SCREAMING_SNAKE_CASE) # verify hidden states self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[1], 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:]) # verify backbone works with out_features=None __lowerCAmelCase : int = None __lowerCAmelCase : Tuple = ConvNextBackbone(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : Dict = model(_SCREAMING_SNAKE_CASE) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def _SCREAMING_SNAKE_CASE ( self: Optional[Any]) -> List[Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = config_and_inputs __lowerCAmelCase : List[str] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class A__ ( A__ , A__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE = ( {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> Dict: """simple docstring""" __lowerCAmelCase : List[str] = ConvNextModelTester(self) __lowerCAmelCase : Optional[int] = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self: Tuple) -> Union[str, Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self: str) -> Union[str, Any]: """simple docstring""" return @unittest.skip(reason="ConvNext does not use inputs_embeds") def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> Dict: """simple docstring""" pass @unittest.skip(reason="ConvNext does not support input and output embeddings") def _SCREAMING_SNAKE_CASE ( self: int) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="ConvNext does not use feedforward chunking") def _SCREAMING_SNAKE_CASE ( self: Dict) -> Any: """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self: Any) -> List[Any]: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase : str = model_class(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase : int = [*signature.parameters.keys()] __lowerCAmelCase : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> Tuple: """simple docstring""" __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> Dict: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Any): __lowerCAmelCase : Optional[Any] = model_class(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() with torch.no_grad(): __lowerCAmelCase : Any = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)) __lowerCAmelCase : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowerCAmelCase : Optional[int] = self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE) , expected_num_stages + 1) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __lowerCAmelCase , __lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase : Union[str, Any] = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCAmelCase : List[Any] = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: List[str]) -> List[str]: """simple docstring""" __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE) @slow def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> List[Any]: """simple docstring""" for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[Any] = ConvNextModel.from_pretrained(_SCREAMING_SNAKE_CASE) self.assertIsNotNone(_SCREAMING_SNAKE_CASE) def _lowercase ( ) -> Any: __lowerCAmelCase : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self: Optional[Any]) -> List[Any]: """simple docstring""" return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224") if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self: Any) -> Tuple: """simple docstring""" __lowerCAmelCase : int = ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224").to(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Any = self.default_image_processor __lowerCAmelCase : List[Any] = prepare_img() __lowerCAmelCase : int = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="pt").to(_SCREAMING_SNAKE_CASE) # forward pass with torch.no_grad(): __lowerCAmelCase : Dict = model(**_SCREAMING_SNAKE_CASE) # verify the logits __lowerCAmelCase : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = torch.tensor([-0.0260, -0.4739, 0.1911]).to(_SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4)) @require_torch class A__ ( unittest.TestCase , A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE = (ConvNextBackbone,) if is_torch_available() else () SCREAMING_SNAKE_CASE = ConvNextConfig SCREAMING_SNAKE_CASE = False def _SCREAMING_SNAKE_CASE ( self: Any) -> int: """simple docstring""" __lowerCAmelCase : List[Any] = ConvNextModelTester(self)
293
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
0
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = ['a', 'b', 'c'] # Defaults to last layer if both are None SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = get_aligned_output_features_output_indices(lowercase__ , lowercase__ , lowercase__ ) self.assertEqual(lowercase__ , ['c'] ) self.assertEqual(lowercase__ , [2] ) # Out indices set to match out features SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_aligned_output_features_output_indices(['a', 'c'] , lowercase__ , lowercase__ ) self.assertEqual(lowercase__ , ['a', 'c'] ) self.assertEqual(lowercase__ , [0, 2] ) # Out features set to match out indices SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = get_aligned_output_features_output_indices(lowercase__ , [0, 2] , lowercase__ ) self.assertEqual(lowercase__ , ['a', 'c'] ) self.assertEqual(lowercase__ , [0, 2] ) # Out features selected from negative indices SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = get_aligned_output_features_output_indices(lowercase__ , [-3, -1] , lowercase__ ) self.assertEqual(lowercase__ , ['a', 'c'] ) self.assertEqual(lowercase__ , [-3, -1] ) def _UpperCamelCase ( self ) -> int: # Stage names must be set with self.assertRaises(lowercase__ ): verify_out_features_out_indices(['a', 'b'] , (0, 1) , lowercase__ ) # Out features must be a list with self.assertRaises(lowercase__ ): verify_out_features_out_indices(('a', 'b') , (0, 1) , ['a', 'b'] ) # Out features must be a subset of stage names with self.assertRaises(lowercase__ ): verify_out_features_out_indices(['a', 'b'] , (0, 1) , ['a'] ) # Out indices must be a list or tuple with self.assertRaises(lowercase__ ): verify_out_features_out_indices(lowercase__ , 0 , ['a', 'b'] ) # Out indices must be a subset of stage names with self.assertRaises(lowercase__ ): verify_out_features_out_indices(lowercase__ , (0, 1) , ['a'] ) # Out features and out indices must be the same length with self.assertRaises(lowercase__ ): verify_out_features_out_indices(['a', 'b'] , (0,) , ['a', 'b', 'c'] ) # Out features should match out indices with self.assertRaises(lowercase__ ): verify_out_features_out_indices(['a', 'b'] , (0, 2) , ['a', 'b', 'c'] ) # Out features and out indices should be in order with self.assertRaises(lowercase__ ): verify_out_features_out_indices(['b', 'a'] , (0, 1) , ['a', 'b'] ) # Check passes with valid inputs verify_out_features_out_indices(['a', 'b', 'd'] , (0, 1, -1) , ['a', 'b', 'c', 'd'] ) def _UpperCamelCase ( self ) -> List[str]: SCREAMING_SNAKE_CASE : Union[str, Any] = BackboneMixin() SCREAMING_SNAKE_CASE : List[str] = ['a', 'b', 'c'] SCREAMING_SNAKE_CASE : int = ['a', 'c'] SCREAMING_SNAKE_CASE : Any = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['a', 'c'] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly SCREAMING_SNAKE_CASE : str = ['a', 'b'] self.assertEqual(backbone.out_features , ['a', 'b'] ) self.assertEqual(backbone.out_indices , [0, 1] ) SCREAMING_SNAKE_CASE : Union[str, Any] = [-3, -1] self.assertEqual(backbone.out_features , ['a', 'c'] ) self.assertEqual(backbone.out_indices , [-3, -1] )
251
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a , **a) elif isinstance(a , a): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.') return self.tokenizer(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''') if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): A__ : Any = ViTImageProcessor if is_vision_available() else None @property def _SCREAMING_SNAKE_CASE (self : str ) -> Dict: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE (self : str ) -> Dict: '''simple docstring''' snake_case : int = (3, 32, 1_28) snake_case : Tuple = tempfile.mkdtemp() # fmt: off snake_case : Tuple = ["[GO]", "[s]", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] # fmt: on snake_case : Any = dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) snake_case : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(snake_case__ ) + "\n" ) snake_case : List[Any] = { "do_normalize": False, "do_resize": True, "image_processor_type": "ViTImageProcessor", "resample": 3, "size": {"height": 32, "width": 1_28}, } snake_case : Optional[int] = os.path.join(self.tmpdirname , snake_case__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Dict , **snake_case__ : Any ) -> List[Any]: '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Union[str, Any] , **snake_case__ : Union[str, Any] ) -> Dict: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Tuple ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _SCREAMING_SNAKE_CASE (self : int ) -> List[str]: '''simple docstring''' snake_case : Tuple = np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta ) snake_case : Union[str, Any] = Image.fromarray(np.moveaxis(snake_case__ , 0 , -1 ) ) return image_input def _SCREAMING_SNAKE_CASE (self : str ) -> Optional[int]: '''simple docstring''' snake_case : Dict = self.get_tokenizer() snake_case : Union[str, Any] = self.get_image_processor() snake_case : Union[str, Any] = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) processor.save_pretrained(self.tmpdirname ) snake_case : Dict = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=snake_case__ ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , snake_case__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> str: '''simple docstring''' snake_case : int = self.get_tokenizer() snake_case : Any = self.get_image_processor() snake_case : Tuple = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) processor.save_pretrained(self.tmpdirname ) snake_case : Optional[int] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) snake_case : Union[str, Any] = self.get_image_processor(do_normalize=snake_case__ , padding_value=1.0 ) snake_case : List[str] = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=snake_case__ , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , snake_case__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> Dict: '''simple docstring''' snake_case : List[Any] = self.get_image_processor() snake_case : List[Any] = self.get_tokenizer() snake_case : Optional[int] = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) snake_case : Any = self.prepare_image_inputs() snake_case : List[Any] = image_processor(snake_case__ , return_tensors="np" ) snake_case : List[str] = processor(images=snake_case__ , return_tensors="np" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _SCREAMING_SNAKE_CASE (self : Dict ) -> List[Any]: '''simple docstring''' snake_case : Optional[int] = self.get_image_processor() snake_case : Any = self.get_tokenizer() snake_case : int = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) snake_case : Optional[Any] = "test" snake_case : Union[str, Any] = processor(text=snake_case__ ) snake_case : List[Any] = tokenizer(snake_case__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _SCREAMING_SNAKE_CASE (self : Dict ) -> str: '''simple docstring''' snake_case : Union[str, Any] = self.get_image_processor() snake_case : Any = self.get_tokenizer() snake_case : Tuple = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) snake_case : Optional[int] = "test" snake_case : List[str] = self.prepare_image_inputs() snake_case : Tuple = processor(text=snake_case__ , images=snake_case__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "labels"] ) # test if it raises when no input is passed with pytest.raises(snake_case__ ): processor() def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> str: '''simple docstring''' snake_case : str = self.get_image_processor() snake_case : int = self.get_tokenizer() snake_case : str = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) snake_case : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] snake_case : Optional[Any] = processor.char_decode(snake_case__ ) snake_case : int = tokenizer.batch_decode(snake_case__ ) snake_case : Any = [seq.replace(" " , "" ) for seq in decoded_tok] self.assertListEqual(snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> Any: '''simple docstring''' snake_case : Optional[int] = self.get_image_processor() snake_case : int = self.get_tokenizer() snake_case : Dict = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) snake_case : List[str] = None snake_case : Optional[Any] = self.prepare_image_inputs() snake_case : Optional[int] = processor(text=snake_case__ , images=snake_case__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def _SCREAMING_SNAKE_CASE (self : int ) -> Tuple: '''simple docstring''' snake_case : str = self.get_image_processor() snake_case : int = self.get_tokenizer() snake_case : Optional[int] = MgpstrProcessor(tokenizer=snake_case__ , image_processor=snake_case__ ) snake_case : Optional[int] = torch.randn(1 , 27 , 38 ) snake_case : Dict = torch.randn(1 , 27 , 5_02_57 ) snake_case : List[str] = torch.randn(1 , 27 , 3_05_22 ) snake_case : Tuple = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ["generated_text", "scores", "char_preds", "bpe_preds", "wp_preds"] )
204
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class _snake_case : # setable values _A = None _A = None _A = None # sigma(t_i) @classmethod def lowerCAmelCase_ ( cls ) -> int: return cls() @dataclass class _snake_case ( A__ ): _A = 42 _A = 42 _A = 42 class _snake_case ( A__ , A__ ): @property def lowerCAmelCase_ ( self ) -> Optional[int]: return True @register_to_config def __init__( self ,UpperCamelCase = 0.02 ,UpperCamelCase = 100 ,UpperCamelCase = 1.007 ,UpperCamelCase = 80 ,UpperCamelCase = 0.05 ,UpperCamelCase = 50 ,) -> Optional[int]: pass def lowerCAmelCase_ ( self ) -> Optional[Any]: return KarrasVeSchedulerState.create() def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = () ) -> KarrasVeSchedulerState: snake_case__ :Dict = jnp.arange(0 ,UpperCamelCase )[::-1].copy() snake_case__ :Union[str, Any] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=UpperCamelCase ,schedule=jnp.array(UpperCamelCase ,dtype=jnp.floataa ) ,timesteps=UpperCamelCase ,) def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,) -> Tuple[jnp.ndarray, float]: if self.config.s_min <= sigma <= self.config.s_max: snake_case__ :List[Any] = min(self.config.s_churn / state.num_inference_steps ,2**0.5 - 1 ) else: snake_case__ :str = 0 # sample eps ~ N(0, S_noise^2 * I) snake_case__ :int = random.split(UpperCamelCase ,num=1 ) snake_case__ :str = self.config.s_noise * random.normal(key=UpperCamelCase ,shape=sample.shape ) snake_case__ :Dict = sigma + gamma * sigma snake_case__ :List[Any] = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = True ,) -> Union[FlaxKarrasVeOutput, Tuple]: snake_case__ :Any = sample_hat + sigma_hat * model_output snake_case__ :Optional[Any] = (sample_hat - pred_original_sample) / sigma_hat snake_case__ :Union[str, Any] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=UpperCamelCase ,derivative=UpperCamelCase ,state=UpperCamelCase ) def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = True ,) -> Union[FlaxKarrasVeOutput, Tuple]: snake_case__ :Any = sample_prev + sigma_prev * model_output snake_case__ :Any = (sample_prev - pred_original_sample) / sigma_prev snake_case__ :List[Any] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=UpperCamelCase ,derivative=UpperCamelCase ,state=UpperCamelCase ) def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> int: raise NotImplementedError()
241
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
0
"""simple docstring""" from queue import PriorityQueue from typing import Any import numpy as np def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,): for nxt, d in graph[v]: if nxt in visited_forward: continue UpperCAmelCase__ : List[str] = cst_fwd.get(_UpperCAmelCase ,np.inf ) UpperCAmelCase__ : int = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) UpperCAmelCase__ : List[str] = new_cost_f UpperCAmelCase__ : Any = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: UpperCAmelCase__ : Optional[int] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ,_snake_case ): UpperCAmelCase__ : Tuple = -1 UpperCAmelCase__ : Optional[Any] = set() UpperCAmelCase__ : Any = set() UpperCAmelCase__ : List[Any] = {source: 0} UpperCAmelCase__ : str = {destination: 0} UpperCAmelCase__ : Tuple = {source: None} UpperCAmelCase__ : List[str] = {destination: None} UpperCAmelCase__ : Any = PriorityQueue() UpperCAmelCase__ : Tuple = PriorityQueue() UpperCAmelCase__ : List[Any] = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): UpperCAmelCase__ , UpperCAmelCase__ : Dict = queue_forward.get() visited_forward.add(_UpperCAmelCase ) UpperCAmelCase__ , UpperCAmelCase__ : Tuple = queue_backward.get() visited_backward.add(_UpperCAmelCase ) UpperCAmelCase__ : List[str] = pass_and_relaxation( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) UpperCAmelCase__ : Tuple = pass_and_relaxation( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: UpperCAmelCase__ : Dict = shortest_distance return shortest_path_distance UpperCamelCase__ = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } UpperCamelCase__ = { 'B': [['E', 1]], 'C': [['B', 1]], 'D': [['C', 1]], 'F': [['D', 1], ['G', 1]], 'E': [[None, np.inf]], 'G': [['E', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
110
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available lowercase = {'tokenization_herbert': ['HerbertTokenizer']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase = ['HerbertTokenizerFast'] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys lowercase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
198
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
"""simple docstring""" import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __lowercase ( A__): """simple docstring""" def __init__(self , lowercase__ , lowercase__=13 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=2 , lowercase__=99 , lowercase__=0 , lowercase__=32 , lowercase__=5 , lowercase__=4 , lowercase__=0.1 , lowercase__=0.1 , lowercase__=5_12 , lowercase__=12 , lowercase__=2 , lowercase__=0.02 , lowercase__=3 , lowercase__=4 , lowercase__="last" , lowercase__=None , lowercase__=None , ): snake_case_ : Any = parent snake_case_ : Dict = batch_size snake_case_ : str = seq_length snake_case_ : Tuple = is_training snake_case_ : int = use_input_lengths snake_case_ : str = use_token_type_ids snake_case_ : str = use_labels snake_case_ : int = gelu_activation snake_case_ : str = sinusoidal_embeddings snake_case_ : Optional[int] = causal snake_case_ : Optional[int] = asm snake_case_ : str = n_langs snake_case_ : Tuple = vocab_size snake_case_ : Tuple = n_special snake_case_ : Any = hidden_size snake_case_ : List[Any] = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : str = hidden_dropout_prob snake_case_ : List[str] = attention_probs_dropout_prob snake_case_ : Optional[Any] = max_position_embeddings snake_case_ : Optional[int] = type_vocab_size snake_case_ : Optional[Any] = type_sequence_label_size snake_case_ : Optional[Any] = initializer_range snake_case_ : Optional[Any] = num_labels snake_case_ : Tuple = num_choices snake_case_ : Dict = summary_type snake_case_ : Union[str, Any] = use_proj snake_case_ : List[str] = scope def __UpperCamelCase (self ): snake_case_ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ : Optional[int] = None if self.use_input_lengths: snake_case_ : List[Any] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length snake_case_ : Tuple = None if self.use_token_type_ids: snake_case_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) snake_case_ : Optional[int] = None snake_case_ : List[str] = None snake_case_ : str = None if self.use_labels: snake_case_ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ : Tuple = ids_tensor([self.batch_size] , 2 ).float() snake_case_ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ : Optional[int] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __UpperCamelCase (self ): return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): snake_case_ : Tuple = FlaubertModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() snake_case_ : Tuple = model(lowercase__ , lengths=lowercase__ , langs=lowercase__ ) snake_case_ : Any = model(lowercase__ , langs=lowercase__ ) snake_case_ : Union[str, Any] = model(lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): snake_case_ : Dict = FlaubertWithLMHeadModel(lowercase__ ) model.to(lowercase__ ) model.eval() snake_case_ : List[str] = model(lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): snake_case_ : Optional[int] = FlaubertForQuestionAnsweringSimple(lowercase__ ) model.to(lowercase__ ) model.eval() snake_case_ : Tuple = model(lowercase__ ) snake_case_ : List[str] = model(lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ ) 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 , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): snake_case_ : Optional[Any] = FlaubertForQuestionAnswering(lowercase__ ) model.to(lowercase__ ) model.eval() snake_case_ : Optional[int] = model(lowercase__ ) snake_case_ : Tuple = model( lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , cls_index=lowercase__ , is_impossible=lowercase__ , p_mask=lowercase__ , ) snake_case_ : List[str] = model( lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , cls_index=lowercase__ , is_impossible=lowercase__ , ) ((snake_case_ ) , ) : List[Any] = result_with_labels.to_tuple() snake_case_ : Union[str, Any] = model(lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ ) ((snake_case_ ) , ) : List[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): snake_case_ : Tuple = FlaubertForSequenceClassification(lowercase__ ) model.to(lowercase__ ) model.eval() snake_case_ : Optional[Any] = model(lowercase__ ) snake_case_ : Tuple = model(lowercase__ , labels=lowercase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): snake_case_ : List[str] = self.num_labels snake_case_ : Any = FlaubertForTokenClassification(lowercase__ ) model.to(lowercase__ ) model.eval() snake_case_ : Any = model(lowercase__ , attention_mask=lowercase__ , labels=lowercase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): snake_case_ : str = self.num_choices snake_case_ : Optional[Any] = FlaubertForMultipleChoice(config=lowercase__ ) model.to(lowercase__ ) model.eval() snake_case_ : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : Any = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : Dict = model( lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase (self ): snake_case_ : str = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) : List[Any] = config_and_inputs snake_case_ : Optional[Any] = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __lowercase ( A__ , A__ , unittest.TestCase): """simple docstring""" _A : Any = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) _A : Any = ( { '''feature-extraction''': FlaubertModel, '''fill-mask''': FlaubertWithLMHeadModel, '''question-answering''': FlaubertForQuestionAnsweringSimple, '''text-classification''': FlaubertForSequenceClassification, '''token-classification''': FlaubertForTokenClassification, '''zero-shot''': FlaubertForSequenceClassification, } if is_torch_available() else {} ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__=False ): snake_case_ : List[Any] = super()._prepare_for_class(lowercase__ , lowercase__ , return_labels=lowercase__ ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": snake_case_ : str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase__ ) snake_case_ : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase__ ) return inputs_dict def __UpperCamelCase (self ): snake_case_ : List[str] = FlaubertModelTester(self ) snake_case_ : Tuple = ConfigTester(self , config_class=lowercase__ , emb_dim=37 ) def __UpperCamelCase (self ): self.config_tester.run_common_tests() def __UpperCamelCase (self ): snake_case_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*lowercase__ ) def __UpperCamelCase (self ): snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*lowercase__ ) def __UpperCamelCase (self ): snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*lowercase__ ) def __UpperCamelCase (self ): snake_case_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*lowercase__ ) def __UpperCamelCase (self ): snake_case_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*lowercase__ ) def __UpperCamelCase (self ): snake_case_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*lowercase__ ) def __UpperCamelCase (self ): snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*lowercase__ ) @slow def __UpperCamelCase (self ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : List[Any] = FlaubertModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) @slow @require_torch_gpu def __UpperCamelCase (self ): snake_case_ , snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return snake_case_ : Optional[int] = True snake_case_ : Optional[int] = model_class(config=lowercase__ ) snake_case_ : Tuple = self._prepare_for_class(lowercase__ , lowercase__ ) snake_case_ : Any = torch.jit.trace( lowercase__ , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(lowercase__ , os.path.join(lowercase__ , """traced_model.pt""" ) ) snake_case_ : Dict = torch.jit.load(os.path.join(lowercase__ , """traced_model.pt""" ) , map_location=lowercase__ ) loaded(inputs_dict["""input_ids"""].to(lowercase__ ) , inputs_dict["""attention_mask"""].to(lowercase__ ) ) @require_torch class __lowercase ( unittest.TestCase): """simple docstring""" @slow def __UpperCamelCase (self ): snake_case_ : int = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) snake_case_ : str = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) with torch.no_grad(): snake_case_ : Any = model(lowercase__ )[0] snake_case_ : Optional[int] = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , lowercase__ ) snake_case_ : str = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowercase__ , atol=1e-4 ) )
480
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""" ) def _lowercase ( ): """simple docstring""" UpperCamelCase = 10 UpperCamelCase = datasets.Features( { """tokens""": datasets.Sequence(datasets.Value("""string""" ) ), """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""] ) ), """answers""": datasets.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), """id""": datasets.Value("""int64""" ), } ) UpperCamelCase = datasets.Dataset.from_dict( { """tokens""": [["""foo"""] * 5] * n, """labels""": [[1] * 5] * n, """answers""": [{"""answer_start""": [97], """text""": ["""1976"""]}] * 10, """id""": list(range(_UpperCAmelCase ) ), } , features=_UpperCAmelCase , ) return dataset @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """file.arrow""" ) dataset.map(cache_file_name=_UpperCAmelCase ) return filename # FILE_CONTENT + files __snake_case = '\\n Text data.\n Second line of data.' @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt""" UpperCamelCase = FILE_CONTENT with open(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase ) return filename @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" import bza UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.bz2""" UpperCamelCase = bytes(_UpperCAmelCase , """utf-8""" ) with bza.open(_UpperCAmelCase , """wb""" ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" import gzip UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """file.txt.gz""" ) UpperCamelCase = bytes(_UpperCAmelCase , """utf-8""" ) with gzip.open(_UpperCAmelCase , """wb""" ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Dict ): """simple docstring""" if datasets.config.LZ4_AVAILABLE: import lza.frame UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.lz4""" UpperCamelCase = bytes(_UpperCAmelCase , """utf-8""" ) with lza.frame.open(_UpperCAmelCase , """wb""" ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any] ): """simple docstring""" if datasets.config.PY7ZR_AVAILABLE: import pyazr UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.7z""" with pyazr.SevenZipFile(_UpperCAmelCase , """w""" ) as archive: archive.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" import tarfile UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.tar""" with tarfile.TarFile(_UpperCAmelCase , """w""" ) as f: f.add(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" import lzma UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.xz""" UpperCamelCase = bytes(_UpperCAmelCase , """utf-8""" ) with lzma.open(_UpperCAmelCase , """wb""" ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): """simple docstring""" import zipfile UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.txt.zst""" UpperCamelCase = bytes(_UpperCAmelCase , """utf-8""" ) with zstd.open(_UpperCAmelCase , """wb""" ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.xml""" UpperCamelCase = textwrap.dedent( """\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>""" ) with open(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase ) return filename __snake_case = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] __snake_case = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] __snake_case = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } __snake_case = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] __snake_case = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope="""session""" ) def _lowercase ( ): """simple docstring""" return DATA_DICT_OF_LISTS @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[Any] ): """simple docstring""" UpperCamelCase = datasets.Dataset.from_dict(_UpperCAmelCase ) UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.arrow""" ) dataset.map(cache_file_name=_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.sqlite""" ) with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: UpperCamelCase = con.cursor() cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)""" ) for item in DATA: cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)""" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.csv""" ) with open(_UpperCAmelCase , """w""" , newline="""""" ) as f: UpperCamelCase = csv.DictWriter(_UpperCAmelCase , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.csv""" ) with open(_UpperCAmelCase , """w""" , newline="""""" ) as f: UpperCamelCase = csv.DictWriter(_UpperCAmelCase , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" import bza UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.bz2""" with open(_UpperCAmelCase , """rb""" ) as f: UpperCamelCase = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(_UpperCAmelCase , """wb""" ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.basename(csv_path.replace(""".csv""" , """.CSV""" ) ) ) f.write(_UpperCAmelCase , arcname=os.path.basename(csva_path.replace(""".csv""" , """.CSV""" ) ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.csv.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.join("""main_dir""" , os.path.basename(_UpperCAmelCase ) ) ) f.write(_UpperCAmelCase , arcname=os.path.join("""main_dir""" , os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.parquet""" ) UpperCamelCase = pa.schema( { """col_1""": pa.string(), """col_2""": pa.intaa(), """col_3""": pa.floataa(), } ) with open(_UpperCAmelCase , """wb""" ) as f: UpperCamelCase = pq.ParquetWriter(_UpperCAmelCase , schema=_UpperCAmelCase ) UpperCamelCase = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(_UpperCAmelCase ) )] for k in DATA[0]} , schema=_UpperCAmelCase ) writer.write_table(_UpperCAmelCase ) writer.close() return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) UpperCamelCase = {"""data""": DATA} with open(_UpperCAmelCase , """w""" ) as f: json.dump(_UpperCAmelCase , _UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) UpperCamelCase = {"""data""": DATA_DICT_OF_LISTS} with open(_UpperCAmelCase , """w""" ) as f: json.dump(_UpperCAmelCase , _UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl""" ) with open(_UpperCAmelCase , """w""" ) as f: for item in DATA: f.write(json.dumps(_UpperCAmelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.jsonl""" ) with open(_UpperCAmelCase , """w""" ) as f: for item in DATA: f.write(json.dumps(_UpperCAmelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset_312.jsonl""" ) with open(_UpperCAmelCase , """w""" ) as f: for item in DATA_312: f.write(json.dumps(_UpperCAmelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset-str.jsonl""" ) with open(_UpperCAmelCase , """w""" ) as f: for item in DATA_STR: f.write(json.dumps(_UpperCAmelCase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" import gzip UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt.gz""" ) with open(_UpperCAmelCase , """rb""" ) as orig_file: with gzip.open(_UpperCAmelCase , """wb""" ) as zipped_file: zipped_file.writelines(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" import gzip UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.gz""" ) with open(_UpperCAmelCase , """rb""" ) as orig_file: with gzip.open(_UpperCAmelCase , """wb""" ) as zipped_file: zipped_file.writelines(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[Any] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.join("""nested""" , os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.jsonl.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.join("""main_dir""" , os.path.basename(_UpperCAmelCase ) ) ) f.write(_UpperCAmelCase , arcname=os.path.join("""main_dir""" , os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.tar""" with tarfile.TarFile(_UpperCAmelCase , """w""" ) as f: f.add(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) f.add(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.tar""" with tarfile.TarFile(_UpperCAmelCase , """w""" ) as f: f.add(_UpperCAmelCase , arcname=os.path.join("""nested""" , os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] ): """simple docstring""" UpperCamelCase = ["""0""", """1""", """2""", """3"""] UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt""" ) with open(_UpperCAmelCase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] ): """simple docstring""" UpperCamelCase = ["""0""", """1""", """2""", """3"""] UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.txt""" ) with open(_UpperCAmelCase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase = ["""0""", """1""", """2""", """3"""] UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.abc""" with open(_UpperCAmelCase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Dict ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.text.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.text.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.join("""main_dir""" , os.path.basename(_UpperCAmelCase ) ) ) f.write(_UpperCAmelCase , arcname=os.path.join("""main_dir""" , os.path.basename(_UpperCAmelCase ) ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.ext.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.basename("""unsupported.ext""" ) ) f.write(_UpperCAmelCase , arcname=os.path.basename("""unsupported_2.ext""" ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" UpperCamelCase = """\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""] ) UpperCamelCase = str(tmp_path_factory.mktemp("""data""" ) / """dataset_with_unicode_new_lines.txt""" ) with open(_UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(_UpperCAmelCase ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( ): """simple docstring""" return os.path.join("""tests""" , """features""" , """data""" , """test_image_rgb.jpg""" ) @pytest.fixture(scope="""session""" ) def _lowercase ( ): """simple docstring""" return os.path.join("""tests""" , """features""" , """data""" , """test_audio_44100.wav""" ) @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data""" ) / """dataset.img.zip""" with zipfile.ZipFile(_UpperCAmelCase , """w""" ) as f: f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ) ) f.write(_UpperCAmelCase , arcname=os.path.basename(_UpperCAmelCase ).replace(""".jpg""" , """2.jpg""" ) ) return path @pytest.fixture(scope="""session""" ) def _lowercase ( SCREAMING_SNAKE_CASE_ : Tuple ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("""data_dir""" ) (data_dir / "subdir").mkdir() with open(data_dir / """subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden file with open(data_dir / """subdir""" / """.test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / """.subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """.subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) return data_dir
386
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
0
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
87
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
0
"""simple docstring""" import colorsys from PIL import Image # type: ignore def __a ( a, a, a ): """simple docstring""" _a = x _a = y for step in range(_UpperCAmelCase ): # noqa: B007 _a = a * a - b * b + x _a = 2 * a * b + y _a = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def __a ( a ): """simple docstring""" if distance == 1: return (0, 0, 0) else: return (2_5_5, 2_5_5, 2_5_5) def __a ( a ): """simple docstring""" if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_5_5 ) for i in colorsys.hsv_to_rgb(_UpperCAmelCase, 1, 1 ) ) def __a ( a = 8_0_0, a = 6_0_0, a = -0.6, a = 0, a = 3.2, a = 5_0, a = True, ): """simple docstring""" _a = Image.new("RGB", (image_width, image_height) ) _a = img.load() # loop through the image-coordinates for image_x in range(_UpperCAmelCase ): for image_y in range(_UpperCAmelCase ): # determine the figure-coordinates based on the image-coordinates _a = figure_width / image_width * image_height _a = figure_center_x + (image_x / image_width - 0.5) * figure_width _a = figure_center_y + (image_y / image_height - 0.5) * figure_height _a = get_distance(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: _a = get_color_coded_rgb(_UpperCAmelCase ) else: _a = get_black_and_white_rgb(_UpperCAmelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure __SCREAMING_SNAKE_CASE = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
388
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
'''simple docstring''' from typing import Any def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ): """simple docstring""" _validation( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) # Creates data structures and fill initial step a__ = {} a__ = {} for state in states_space: a__ = observations_space[0] a__ = ( initial_probabilities[state] * emission_probabilities[state][observation] ) a__ = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1 , len(_UpperCAmelCase ) ): a__ = observations_space[o] a__ = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function a__ = "" a__ = -1 for k_state in states_space: a__ = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: a__ = probability a__ = k_state # Update probabilities and pointers dicts a__ = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) a__ = arg_max # The final observation a__ = observations_space[len(_UpperCAmelCase ) - 1] # argmax for given final observation a__ = "" a__ = -1 for k_state in states_space: a__ = probabilities[(k_state, final_observation)] if probability > max_probability: a__ = probability a__ = k_state a__ = arg_max # Process pointers backwards a__ = last_state a__ = [] for o in range(len(_UpperCAmelCase ) - 1 , -1 , -1 ): result.append(_UpperCAmelCase ) a__ = pointers[previous, observations_space[o]] result.reverse() return result def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ): """simple docstring""" _validate_not_empty( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) _validate_lists(_UpperCAmelCase , _UpperCAmelCase ) _validate_dicts( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ): """simple docstring""" if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There\'s an empty parameter" ) def _lowerCAmelCase (_lowercase , _lowercase ): """simple docstring""" _validate_list(_UpperCAmelCase , "observations_space" ) _validate_list(_UpperCAmelCase , "states_space" ) def _lowerCAmelCase (_lowercase , _lowercase ): """simple docstring""" if not isinstance(_object , _UpperCAmelCase ): a__ = F'{var_name} must be a list' raise ValueError(_UpperCAmelCase ) else: for x in _object: if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): a__ = F'{var_name} must be a list of strings' raise ValueError(_UpperCAmelCase ) def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , ): """simple docstring""" _validate_dict(_UpperCAmelCase , "initial_probabilities" , _UpperCAmelCase ) _validate_nested_dict(_UpperCAmelCase , "transition_probabilities" ) _validate_nested_dict(_UpperCAmelCase , "emission_probabilities" ) def _lowerCAmelCase (_lowercase , _lowercase ): """simple docstring""" _validate_dict(_object , _UpperCAmelCase , _UpperCAmelCase ) for x in _object.values(): _validate_dict(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase = False ): """simple docstring""" if not isinstance(_object , _UpperCAmelCase ): a__ = F'{var_name} must be a dict' raise ValueError(_UpperCAmelCase ) if not all(isinstance(_UpperCAmelCase , _UpperCAmelCase ) for x in _object ): a__ = F'{var_name} all keys must be strings' raise ValueError(_UpperCAmelCase ) if not all(isinstance(_UpperCAmelCase , _UpperCAmelCase ) for x in _object.values() ): a__ = "nested dictionary " if nested else "" a__ = F'{var_name} {nested_text}all values must be {value_type.__name__}' raise ValueError(_UpperCAmelCase ) if __name__ == "__main__": from doctest import testmod testmod()
331
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : 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=37 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
0
"""simple docstring""" def _lowercase ( __snake_case ) -> Union[str, Any]: if any(not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or x < 0 for x in sequence ): raise TypeError("Sequence must be list of non-negative integers" ) for _ in range(len(_UpperCAmelCase ) ): for i, (rod_upper, rod_lower) in enumerate(zip(_UpperCAmelCase ,sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
293
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class UpperCAmelCase ( A__ ): '''simple docstring''' def __init__( self , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = False , lowercase__ = False , lowercase__ = None , **lowercase__ , ) -> List[str]: SCREAMING_SNAKE_CASE : Dict = path_or_paths SCREAMING_SNAKE_CASE : Any = split if split or isinstance(lowercase__ , lowercase__ ) else 'train' SCREAMING_SNAKE_CASE : List[str] = features SCREAMING_SNAKE_CASE : Dict = cache_dir SCREAMING_SNAKE_CASE : Any = keep_in_memory SCREAMING_SNAKE_CASE : List[Any] = streaming SCREAMING_SNAKE_CASE : Any = num_proc SCREAMING_SNAKE_CASE : Optional[int] = kwargs @abstractmethod def _UpperCamelCase ( self ) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]: pass class UpperCAmelCase ( A__ ): '''simple docstring''' def __init__( self , lowercase__ = None , lowercase__ = None , lowercase__ = False , lowercase__ = False , lowercase__ = None , **lowercase__ , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE : List[str] = features SCREAMING_SNAKE_CASE : List[str] = cache_dir SCREAMING_SNAKE_CASE : Any = keep_in_memory SCREAMING_SNAKE_CASE : int = streaming SCREAMING_SNAKE_CASE : int = num_proc SCREAMING_SNAKE_CASE : Tuple = kwargs @abstractmethod def _UpperCamelCase ( self ) -> Union[Dataset, IterableDataset]: pass
251
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) 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.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
from math import pi def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : Any ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
204
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester 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 __UpperCAmelCase : Tuple = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class _snake_case : _A = PegasusConfig _A = {} _A = '''gelu''' def __init__( self ,UpperCamelCase ,UpperCamelCase=13 ,UpperCamelCase=7 ,UpperCamelCase=True ,UpperCamelCase=False ,UpperCamelCase=99 ,UpperCamelCase=32 ,UpperCamelCase=5 ,UpperCamelCase=4 ,UpperCamelCase=37 ,UpperCamelCase=0.1 ,UpperCamelCase=0.1 ,UpperCamelCase=20 ,UpperCamelCase=2 ,UpperCamelCase=1 ,UpperCamelCase=0 ,) -> int: snake_case__ :Optional[Any] = parent snake_case__ :Optional[Any] = batch_size snake_case__ :Optional[Any] = seq_length snake_case__ :int = is_training snake_case__ :List[str] = use_labels snake_case__ :List[Any] = vocab_size snake_case__ :List[Any] = hidden_size snake_case__ :Any = num_hidden_layers snake_case__ :Dict = num_attention_heads snake_case__ :Tuple = intermediate_size snake_case__ :str = hidden_dropout_prob snake_case__ :List[str] = attention_probs_dropout_prob snake_case__ :List[Any] = max_position_embeddings snake_case__ :Union[str, Any] = eos_token_id snake_case__ :Optional[int] = pad_token_id snake_case__ :Optional[Any] = bos_token_id def lowerCAmelCase_ ( self ) -> Optional[Any]: snake_case__ :int = ids_tensor([self.batch_size, self.seq_length - 1] ,self.vocab_size ).clip(3 ,self.vocab_size ) snake_case__ :Tuple = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) ,1 ) snake_case__ :Dict = np.concatenate([input_ids, eos_tensor] ,axis=1 ) snake_case__ :List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) snake_case__ :Any = self.config_cls( vocab_size=self.vocab_size ,d_model=self.hidden_size ,encoder_layers=self.num_hidden_layers ,decoder_layers=self.num_hidden_layers ,encoder_attention_heads=self.num_attention_heads ,decoder_attention_heads=self.num_attention_heads ,encoder_ffn_dim=self.intermediate_size ,decoder_ffn_dim=self.intermediate_size ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,eos_token_ids=[2] ,bos_token_id=self.bos_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.pad_token_id ,**self.config_updates ,) snake_case__ :Optional[int] = prepare_pegasus_inputs_dict(UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) return config, inputs_dict def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> str: snake_case__ :Dict = 20 snake_case__ :Optional[int] = model_class_name(UpperCamelCase ) snake_case__ :str = model.encode(inputs_dict["input_ids"] ) snake_case__ , snake_case__ :Union[str, Any] = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) snake_case__ :Dict = model.init_cache(decoder_input_ids.shape[0] ,UpperCamelCase ,UpperCamelCase ) snake_case__ :Union[str, Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) ,dtype="i4" ) snake_case__ :Tuple = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] ,(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) ,) snake_case__ :Union[str, Any] = model.decode( decoder_input_ids[:, :-1] ,UpperCamelCase ,decoder_attention_mask=UpperCamelCase ,past_key_values=UpperCamelCase ,decoder_position_ids=UpperCamelCase ,) snake_case__ :Optional[Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] ,dtype="i4" ) snake_case__ :Any = model.decode( decoder_input_ids[:, -1:] ,UpperCamelCase ,decoder_attention_mask=UpperCamelCase ,past_key_values=outputs_cache.past_key_values ,decoder_position_ids=UpperCamelCase ,) snake_case__ :str = model.decode(UpperCamelCase ,UpperCamelCase ) snake_case__ :Tuple = 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 lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> Any: snake_case__ :Any = 20 snake_case__ :Tuple = model_class_name(UpperCamelCase ) snake_case__ :Optional[Any] = model.encode(inputs_dict["input_ids"] ) snake_case__ , snake_case__ :Optional[Any] = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) snake_case__ :str = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] ,axis=-1 ,) snake_case__ :str = model.init_cache(decoder_input_ids.shape[0] ,UpperCamelCase ,UpperCamelCase ) snake_case__ :Union[str, Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] ,(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) ,) snake_case__ :Dict = model.decode( decoder_input_ids[:, :-1] ,UpperCamelCase ,decoder_attention_mask=UpperCamelCase ,past_key_values=UpperCamelCase ,decoder_position_ids=UpperCamelCase ,) snake_case__ :Optional[Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] ,dtype="i4" ) snake_case__ :Any = model.decode( decoder_input_ids[:, -1:] ,UpperCamelCase ,past_key_values=outputs_cache.past_key_values ,decoder_attention_mask=UpperCamelCase ,decoder_position_ids=UpperCamelCase ,) snake_case__ :str = model.decode(UpperCamelCase ,UpperCamelCase ,decoder_attention_mask=UpperCamelCase ) snake_case__ :Union[str, Any] = 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 lowercase_ ( __snake_case : int , __snake_case : List[str] , __snake_case : int , __snake_case : str=None , __snake_case : Dict=None , ) -> Tuple: '''simple docstring''' if attention_mask is None: snake_case__ :int = np.not_equal(_UpperCAmelCase , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: snake_case__ :Tuple = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class _snake_case ( A__ , unittest.TestCase ): _A = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) _A = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () _A = True _A = False _A = False _A = False def lowerCAmelCase_ ( self ) -> Optional[int]: snake_case__ :List[str] = FlaxPegasusModelTester(self ) snake_case__ :Tuple = ConfigTester(self ,config_class=UpperCamelCase ) def lowerCAmelCase_ ( self ) -> Optional[int]: self.config_tester.run_common_tests() def lowerCAmelCase_ ( self ) -> int: snake_case__ , snake_case__ :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) def lowerCAmelCase_ ( self ) -> List[Any]: snake_case__ , snake_case__ :str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) def lowerCAmelCase_ ( self ) -> Any: snake_case__ , snake_case__ :Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case__ :Optional[Any] = self._prepare_for_class(UpperCamelCase ,UpperCamelCase ) snake_case__ :Any = model_class(UpperCamelCase ) @jax.jit def encode_jitted(UpperCamelCase ,UpperCamelCase=None ,**UpperCamelCase ): return model.encode(input_ids=UpperCamelCase ,attention_mask=UpperCamelCase ) with self.subTest("JIT Enabled" ): snake_case__ :List[Any] = encode_jitted(**UpperCamelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): snake_case__ :Dict = encode_jitted(**UpperCamelCase ).to_tuple() self.assertEqual(len(UpperCamelCase ) ,len(UpperCamelCase ) ) for jitted_output, output in zip(UpperCamelCase ,UpperCamelCase ): self.assertEqual(jitted_output.shape ,output.shape ) def lowerCAmelCase_ ( self ) -> Union[str, Any]: snake_case__ , snake_case__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case__ :str = model_class(UpperCamelCase ) snake_case__ :Union[str, Any] = model.encode(inputs_dict["input_ids"] ,inputs_dict["attention_mask"] ) snake_case__ :Optional[Any] = { "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(UpperCamelCase ,UpperCamelCase ,UpperCamelCase ): return model.decode( decoder_input_ids=UpperCamelCase ,decoder_attention_mask=UpperCamelCase ,encoder_outputs=UpperCamelCase ,) with self.subTest("JIT Enabled" ): snake_case__ :int = decode_jitted(**UpperCamelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): snake_case__ :int = decode_jitted(**UpperCamelCase ).to_tuple() self.assertEqual(len(UpperCamelCase ) ,len(UpperCamelCase ) ) for jitted_output, output in zip(UpperCamelCase ,UpperCamelCase ): self.assertEqual(jitted_output.shape ,output.shape ) @slow def lowerCAmelCase_ ( self ) -> List[Any]: for model_class_name in self.all_model_classes: snake_case__ :Optional[int] = model_class_name.from_pretrained("google/pegasus-large" ,from_pt=UpperCamelCase ) snake_case__ :List[str] = np.ones((1, 1) ) snake_case__ :Union[str, Any] = model(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) @slow def lowerCAmelCase_ ( self ) -> Any: snake_case__ :Optional[int] = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" ) snake_case__ :int = PegasusTokenizer.from_pretrained("google/pegasus-xsum" ) snake_case__ :Any = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning \'Oh I think you\'re nominated\'\", said Dappy.\"And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around.\"At the end of the day we\'re grateful to be where we are in our careers.\"If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] snake_case__ :List[Any] = [ "California\'s largest electricity provider has turned off power to hundreds of thousands of customers.", "Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.", ] snake_case__ :Dict = tokenizer(UpperCamelCase ,return_tensors="np" ,truncation=UpperCamelCase ,max_length=512 ,padding=UpperCamelCase ) snake_case__ :Dict = model.generate(**UpperCamelCase ,num_beams=2 ).sequences snake_case__ :Optional[int] = tokenizer.batch_decode(UpperCamelCase ,skip_special_tokens=UpperCamelCase ) assert tgt_text == decoded
241
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class a ( ctypes.Structure ): # _fields is a specific attr expected by ctypes UpperCamelCase : Tuple = [('''size''', ctypes.c_int), ('''visible''', ctypes.c_byte)] def lowerCamelCase ( ): if os.name == "nt": UpperCAmelCase__ : List[str] = CursorInfo() UpperCAmelCase__ : Dict = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCAmelCase ,ctypes.byref(_UpperCAmelCase ) ) UpperCAmelCase__ : str = False ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCAmelCase ,ctypes.byref(_UpperCAmelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25l' ) sys.stdout.flush() def lowerCamelCase ( ): if os.name == "nt": UpperCAmelCase__ : str = CursorInfo() UpperCAmelCase__ : int = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCAmelCase ,ctypes.byref(_UpperCAmelCase ) ) UpperCAmelCase__ : List[str] = True ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCAmelCase ,ctypes.byref(_UpperCAmelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25h' ) sys.stdout.flush() @contextmanager def lowerCamelCase ( ): try: hide_cursor() yield finally: show_cursor()
110
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING lowercase = logging.get_logger(__name__) @add_end_docstrings(A__ ) class UpperCamelCase_ ( A__ ): '''simple docstring''' def __init__( self , *a , **a ) -> Tuple: super().__init__(*a , **a ) requires_backends(self , 'decord' ) self.check_model_type(a ) def _UpperCamelCase ( self , a=None , a=None , a=None ) -> Any: snake_case_ = {} if frame_sampling_rate is not None: snake_case_ = frame_sampling_rate if num_frames is not None: snake_case_ = num_frames snake_case_ = {} if top_k is not None: snake_case_ = top_k return preprocess_params, {}, postprocess_params def __call__( self , a , **a ) -> Union[str, Any]: return super().__call__(a , **a ) def _UpperCamelCase ( self , a , a=None , a=1 ) -> List[str]: if num_frames is None: snake_case_ = self.model.config.num_frames if video.startswith('http://' ) or video.startswith('https://' ): snake_case_ = BytesIO(requests.get(a ).content ) snake_case_ = VideoReader(a ) videoreader.seek(0 ) snake_case_ = 0 snake_case_ = num_frames * frame_sampling_rate - 1 snake_case_ = np.linspace(a , a , num=a , dtype=np.intaa ) snake_case_ = videoreader.get_batch(a ).asnumpy() snake_case_ = list(a ) snake_case_ = self.image_processor(a , return_tensors=self.framework ) return model_inputs def _UpperCamelCase ( self , a ) -> Dict: snake_case_ = self.model(**a ) return model_outputs def _UpperCamelCase ( self , a , a=5 ) -> Optional[Any]: if top_k > self.model.config.num_labels: snake_case_ = self.model.config.num_labels if self.framework == "pt": snake_case_ = model_outputs.logits.softmax(-1 )[0] snake_case_ , snake_case_ = probs.topk(a ) else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) snake_case_ = scores.tolist() snake_case_ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(a , a )]
198
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
"""simple docstring""" import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowercase ( A__ , unittest.TestCase): """simple docstring""" _A : Tuple = FunnelTokenizer _A : Union[str, Any] = FunnelTokenizerFast _A : Dict = True _A : Union[str, Any] = True def __UpperCamelCase (self ): super().setUp() snake_case_ : List[Any] = [ """<unk>""", """<cls>""", """<sep>""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] snake_case_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def __UpperCamelCase (self , **lowercase__ ): return FunnelTokenizer.from_pretrained(self.tmpdirname , **lowercase__ ) def __UpperCamelCase (self , **lowercase__ ): return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **lowercase__ ) def __UpperCamelCase (self , lowercase__ ): snake_case_ : Any = """UNwant\u00E9d,running""" snake_case_ : Any = """unwanted, running""" return input_text, output_text def __UpperCamelCase (self ): snake_case_ : Union[str, Any] = self.tokenizer_class(self.vocab_file ) snake_case_ : Dict = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(lowercase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__ ) , [7, 4, 5, 10, 8, 9] ) def __UpperCamelCase (self ): snake_case_ : str = self.get_tokenizers(do_lower_case=lowercase__ ) for tokenizer in tokenizers: snake_case_ : List[str] = tokenizer("""UNwant\u00E9d,running""" ) snake_case_ : Any = len(inputs["""input_ids"""] ) - 1 self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len ) snake_case_ : Union[str, Any] = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" ) self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
480
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
0
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class UpperCAmelCase ( A__ ): def __init__( self : Dict , __magic_name__ : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : List[Any] ): """simple docstring""" UpperCamelCase = dataset UpperCamelCase = process UpperCamelCase = params def __len__( self : Optional[int] ): """simple docstring""" return len(self.dataset ) def __getitem__( self : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.dataset[i] UpperCamelCase = self.process(__magic_name__ , **self.params ) return processed class UpperCAmelCase ( A__ ): def __init__( self : Dict , __magic_name__ : List[Any] , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : Dict=None ): """simple docstring""" UpperCamelCase = loader UpperCamelCase = infer UpperCamelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether UpperCamelCase = None UpperCamelCase = loader_batch_size # Internal bookkeeping UpperCamelCase = None UpperCamelCase = None def __len__( self : Tuple ): """simple docstring""" return len(self.loader ) def __iter__( self : Dict ): """simple docstring""" UpperCamelCase = iter(self.loader ) return self def lowerCamelCase_ ( self : str ): """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice UpperCamelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) UpperCamelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(__magic_name__ , __magic_name__ ): # Convert ModelOutput to tuple first UpperCamelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(__magic_name__ , __magic_name__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): UpperCamelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCamelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around UpperCamelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCamelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCamelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. UpperCamelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 UpperCamelCase = self._loader_batch_data.__class__(__magic_name__ ) self._loader_batch_index += 1 return result def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch UpperCamelCase = next(self.iterator ) UpperCamelCase = self.infer(__magic_name__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(__magic_name__ , torch.Tensor ): UpperCamelCase = processed else: UpperCamelCase = list(processed.keys() )[0] UpperCamelCase = processed[key] if isinstance(__magic_name__ , __magic_name__ ): UpperCamelCase = len(__magic_name__ ) else: UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCamelCase = observed_batch_size # Setting internal index to unwrap the batch UpperCamelCase = processed UpperCamelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class UpperCAmelCase ( A__ ): def __init__( self : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[int]=None ): """simple docstring""" super().__init__(__magic_name__ , __magic_name__ , __magic_name__ ) def __iter__( self : Any ): """simple docstring""" UpperCamelCase = iter(self.loader ) UpperCamelCase = None return self def lowerCamelCase_ ( self : str ): """simple docstring""" if self.subiterator is None: UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item UpperCamelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) UpperCamelCase = next(self.subiterator ) return processed class UpperCAmelCase ( A__ ): def __iter__( self : str ): """simple docstring""" UpperCamelCase = iter(self.loader ) return self def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = False UpperCamelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: UpperCamelCase = self.loader_batch_item() UpperCamelCase = item.pop("""is_last""" ) accumulator.append(__magic_name__ ) if is_last: return accumulator while not is_last: UpperCamelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(__magic_name__ , torch.Tensor ): UpperCamelCase = processed else: UpperCamelCase = list(processed.keys() )[0] UpperCamelCase = processed[key] if isinstance(__magic_name__ , __magic_name__ ): UpperCamelCase = len(__magic_name__ ) else: UpperCamelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCamelCase = observed_batch_size UpperCamelCase = processed UpperCamelCase = 0 while self._loader_batch_index < self.loader_batch_size: UpperCamelCase = self.loader_batch_item() UpperCamelCase = item.pop("""is_last""" ) accumulator.append(__magic_name__ ) if is_last: return accumulator else: UpperCamelCase = processed UpperCamelCase = item.pop("""is_last""" ) accumulator.append(__magic_name__ ) return accumulator class UpperCAmelCase ( A__ ): def __init__( self : str , __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" UpperCamelCase = dataset UpperCamelCase = key def __len__( self : str ): """simple docstring""" return len(self.dataset ) def __getitem__( self : List[Any] , __magic_name__ : Optional[Any] ): """simple docstring""" return self.dataset[i][self.key] class UpperCAmelCase ( A__ ): def __init__( self : List[str] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : int ): """simple docstring""" UpperCamelCase = dataset UpperCamelCase = keya UpperCamelCase = keya def __len__( self : List[str] ): """simple docstring""" return len(self.dataset ) def __getitem__( self : List[str] , __magic_name__ : int ): """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
386
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
0
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class UpperCamelCase_ ( A__ ): '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , ) ->Tuple: '''simple docstring''' super().__init__() A__ = value_function A__ = unet A__ = scheduler A__ = env A__ = env.get_dataset() A__ = {} for key in self.data.keys(): try: A__ = self.data[key].mean() except: # noqa: E722 pass A__ = {} for key in self.data.keys(): try: A__ = self.data[key].std() except: # noqa: E722 pass A__ = env.observation_space.shape[0] A__ = env.action_space.shape[0] def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any]) ->Tuple: '''simple docstring''' return (x_in - self.means[key]) / self.stds[key] def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Any) ->List[str]: '''simple docstring''' return x_in * self.stds[key] + self.means[key] def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : List[str]) ->Optional[Any]: '''simple docstring''' if type(UpperCAmelCase__) is dict: return {k: self.to_torch(UpperCAmelCase__) for k, v in x_in.items()} elif torch.is_tensor(UpperCAmelCase__): return x_in.to(self.unet.device) return torch.tensor(UpperCAmelCase__ , device=self.unet.device) def SCREAMING_SNAKE_CASE ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any]) ->List[Any]: '''simple docstring''' for key, val in cond.items(): A__ = val.clone() return x_in def SCREAMING_SNAKE_CASE ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[Any]) ->str: '''simple docstring''' A__ = x.shape[0] A__ = None for i in tqdm.tqdm(self.scheduler.timesteps): # create batch of timesteps to pass into model A__ = torch.full((batch_size,) , UpperCAmelCase__ , device=self.unet.device , dtype=torch.long) for _ in range(UpperCAmelCase__): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models A__ = self.value_function(x.permute(0 , 2 , 1) , UpperCAmelCase__).sample A__ = torch.autograd.grad([y.sum()] , [x])[0] A__ = self.scheduler._get_variance(UpperCAmelCase__) A__ = torch.exp(0.5 * posterior_variance) A__ = model_std * grad A__ = 0 A__ = x.detach() A__ = x + scale * grad A__ = self.reset_xa(UpperCAmelCase__ , UpperCAmelCase__ , self.action_dim) A__ = self.unet(x.permute(0 , 2 , 1) , UpperCAmelCase__).sample.permute(0 , 2 , 1) # TODO: verify deprecation of this kwarg A__ = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , predict_epsilon=UpperCAmelCase__)['''prev_sample'''] # apply conditions to the trajectory (set the initial state) A__ = self.reset_xa(UpperCAmelCase__ , UpperCAmelCase__ , self.action_dim) A__ = self.to_torch(UpperCAmelCase__) return x, y def __call__( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict=64 , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : Any=0.1) ->Optional[Any]: '''simple docstring''' A__ = self.normalize(UpperCAmelCase__ , '''observations''') A__ = obs[None].repeat(UpperCAmelCase__ , axis=0) A__ = {0: self.to_torch(UpperCAmelCase__)} A__ = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) A__ = randn_tensor(UpperCAmelCase__ , device=self.unet.device) A__ = self.reset_xa(UpperCAmelCase__ , UpperCAmelCase__ , self.action_dim) A__ = self.to_torch(UpperCAmelCase__) # run the diffusion process A__ , A__ = self.run_diffusion(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) # sort output trajectories by value A__ = y.argsort(0 , descending=UpperCAmelCase__).squeeze() A__ = x[sorted_idx] A__ = sorted_values[:, :, : self.action_dim] A__ = actions.detach().cpu().numpy() A__ = self.de_normalize(UpperCAmelCase__ , key='''actions''') # select the action with the highest value if y is not None: A__ = 0 else: # if we didn't run value guiding, select a random action A__ = np.random.randint(0 , UpperCAmelCase__) A__ = denorm_actions[selected_index, 0] return denorm_actions
87
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class __snake_case ( unittest.TestCase , A__ ): """simple docstring""" def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): _a = load_tool("text-classification" ) self.tool.setup() _a = load_tool("text-classification" , remote=UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): _a = self.tool("That\'s quite cool" , ["positive", "negative"] ) self.assertEqual(UpperCamelCase__ , "positive" ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): _a = self.remote_tool("That\'s quite cool" , ["positive", "negative"] ) self.assertEqual(UpperCamelCase__ , "positive" ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): _a = self.tool(text="That\'s quite cool" , labels=["positive", "negative"] ) self.assertEqual(UpperCamelCase__ , "positive" ) def SCREAMING_SNAKE_CASE_ ( self :str ): _a = self.remote_tool(text="That\'s quite cool" , labels=["positive", "negative"] ) self.assertEqual(UpperCamelCase__ , "positive" )
388
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
0
'''simple docstring''' import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCamelCase_ : int = logging.getLogger(__name__) if __name__ == "__main__": UpperCamelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30_522, type=int) UpperCamelCase_ : Union[str, Any] = parser.parse_args() logger.info(F"Loading data from {args.data_file}") with open(args.data_file, """rb""") as fp: UpperCamelCase_ : Any = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCamelCase_ : int = Counter() for tk_ids in data: counter.update(tk_ids) UpperCamelCase_ : Optional[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCamelCase_ : Dict = v logger.info(F"Dump to {args.token_counts_dump}") with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
331
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __snake_case : int = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class A__ ( datasets.BuilderConfig ): '''simple docstring''' SCREAMING_SNAKE_CASE = None def _lowercase ( __snake_case ,__snake_case ,) -> Any: import pyspark def generate_fn(): __lowerCAmelCase : int = df.select("*" ,pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: __lowerCAmelCase : Any = df_with_partition_id.select("*" ).where(F"""part_id = {partition_id}""" ).drop("part_id" ) __lowerCAmelCase : List[Any] = partition_df.collect() __lowerCAmelCase : Union[str, Any] = 0 for row in rows: yield F"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class A__ ( _BaseExamplesIterable ): '''simple docstring''' def __init__( self: str , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Any=None , ) -> Tuple: """simple docstring""" __lowerCAmelCase : Optional[Any] = df __lowerCAmelCase : Tuple = partition_order or range(self.df.rdd.getNumPartitions()) __lowerCAmelCase : List[Any] = _generate_iterable_examples(self.df , self.partition_order) def __iter__( self: Optional[int]) -> Dict: """simple docstring""" yield from self.generate_examples_fn() def _SCREAMING_SNAKE_CASE ( self: List[str] , _SCREAMING_SNAKE_CASE: List[str]) -> "SparkExamplesIterable": """simple docstring""" __lowerCAmelCase : str = list(range(self.df.rdd.getNumPartitions())) generator.shuffle(_SCREAMING_SNAKE_CASE) return SparkExamplesIterable(self.df , partition_order=_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Tuple , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: List[Any]) -> "SparkExamplesIterable": """simple docstring""" __lowerCAmelCase : List[str] = self.split_shard_indices_by_worker(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) return SparkExamplesIterable(self.df , partition_order=_SCREAMING_SNAKE_CASE) @property def _SCREAMING_SNAKE_CASE ( self: Tuple) -> int: """simple docstring""" return len(self.partition_order) class A__ ( datasets.DatasetBuilder ): '''simple docstring''' SCREAMING_SNAKE_CASE = SparkConfig def __init__( self: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: int = None , _SCREAMING_SNAKE_CASE: List[Any] = None , **_SCREAMING_SNAKE_CASE: Union[str, Any] , ) -> List[Any]: """simple docstring""" import pyspark __lowerCAmelCase : str = pyspark.sql.SparkSession.builder.getOrCreate() __lowerCAmelCase : Optional[Any] = df __lowerCAmelCase : List[Any] = working_dir super().__init__( cache_dir=_SCREAMING_SNAKE_CASE , config_name=str(self.df.semanticHash()) , **_SCREAMING_SNAKE_CASE , ) def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Any: """simple docstring""" def create_cache_and_write_probe(_SCREAMING_SNAKE_CASE: Union[str, Any]): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = os.path.join(self._cache_dir , "fs_test" + uuid.uuida().hex) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(_SCREAMING_SNAKE_CASE , "a") return [probe_file] if self._spark.conf.get("spark.master" , "").startswith("local"): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __lowerCAmelCase : List[Any] = ( self._spark.sparkContext.parallelize(range(1) , 1).mapPartitions(_SCREAMING_SNAKE_CASE).collect() ) if os.path.isfile(probe[0]): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir") def _SCREAMING_SNAKE_CASE ( self: Any) -> Dict: """simple docstring""" return datasets.DatasetInfo(features=self.config.features) def _SCREAMING_SNAKE_CASE ( self: int , _SCREAMING_SNAKE_CASE: Optional[int]) -> Optional[int]: """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN)] def _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> Union[str, Any]: """simple docstring""" import pyspark def get_arrow_batch_size(_SCREAMING_SNAKE_CASE: Optional[int]): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]}) __lowerCAmelCase : Any = self.df.count() __lowerCAmelCase : Tuple = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __lowerCAmelCase : int = ( self.df.limit(_SCREAMING_SNAKE_CASE) .repartition(1) .mapInArrow(_SCREAMING_SNAKE_CASE , "batch_bytes: long") .agg(pyspark.sql.functions.sum("batch_bytes").alias("sample_bytes")) .collect()[0] .sample_bytes / sample_num_rows ) __lowerCAmelCase : List[Any] = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __lowerCAmelCase : Dict = min(_SCREAMING_SNAKE_CASE , int(approx_total_size / max_shard_size)) __lowerCAmelCase : int = self.df.repartition(_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: int , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: """simple docstring""" import pyspark __lowerCAmelCase : Optional[Any] = ParquetWriter if file_format == "parquet" else ArrowWriter __lowerCAmelCase : Optional[Any] = os.path.join(self._working_dir , os.path.basename(_SCREAMING_SNAKE_CASE)) if self._working_dir else fpath __lowerCAmelCase : Tuple = file_format == "parquet" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __lowerCAmelCase : str = self.config.features __lowerCAmelCase : Optional[Any] = self._writer_batch_size __lowerCAmelCase : str = self._fs.storage_options def write_arrow(_SCREAMING_SNAKE_CASE: Union[str, Any]): # Within the same SparkContext, no two task attempts will share the same attempt ID. __lowerCAmelCase : Optional[int] = pyspark.TaskContext().taskAttemptId() __lowerCAmelCase : Dict = next(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["task_id", "num_examples", "num_bytes"] , ) __lowerCAmelCase : int = 0 __lowerCAmelCase : str = writer_class( features=_SCREAMING_SNAKE_CASE , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""").replace("TTTTT" , F"""{task_id:05d}""") , writer_batch_size=_SCREAMING_SNAKE_CASE , storage_options=_SCREAMING_SNAKE_CASE , embed_local_files=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Optional[Any] = pa.Table.from_batches([first_batch]) writer.write_table(_SCREAMING_SNAKE_CASE) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __lowerCAmelCase , __lowerCAmelCase : Any = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) shard_id += 1 __lowerCAmelCase : Dict = writer_class( features=writer._features , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""").replace("TTTTT" , F"""{task_id:05d}""") , writer_batch_size=_SCREAMING_SNAKE_CASE , storage_options=_SCREAMING_SNAKE_CASE , embed_local_files=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Optional[Any] = pa.Table.from_batches([batch]) writer.write_table(_SCREAMING_SNAKE_CASE) if writer._num_bytes > 0: __lowerCAmelCase , __lowerCAmelCase : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(_SCREAMING_SNAKE_CASE)): __lowerCAmelCase : Union[str, Any] = os.path.join(os.path.dirname(_SCREAMING_SNAKE_CASE) , os.path.basename(_SCREAMING_SNAKE_CASE)) shutil.move(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = ( self.df.mapInArrow(_SCREAMING_SNAKE_CASE , "task_id: long, num_examples: long, num_bytes: long") .groupBy("task_id") .agg( pyspark.sql.functions.sum("num_examples").alias("total_num_examples") , pyspark.sql.functions.sum("num_bytes").alias("total_num_bytes") , pyspark.sql.functions.count("num_bytes").alias("num_shards") , pyspark.sql.functions.collect_list("num_examples").alias("shard_lengths") , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _SCREAMING_SNAKE_CASE ( self: Tuple , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: str = "arrow" , _SCREAMING_SNAKE_CASE: Tuple = None , _SCREAMING_SNAKE_CASE: List[Any] = None , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> List[str]: """simple docstring""" self._validate_cache_dir() __lowerCAmelCase : List[str] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE) self._repartition_df_if_needed(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = not is_remote_filesystem(self._fs) __lowerCAmelCase : int = os.path.join if is_local else posixpath.join __lowerCAmelCase : Optional[int] = "-TTTTT-SSSSS-of-NNNNN" __lowerCAmelCase : Tuple = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" __lowerCAmelCase : Optional[Any] = path_join(self._output_dir , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Any = 0 __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Any = 0 __lowerCAmelCase : Any = [] __lowerCAmelCase : int = [] for task_id, content in self._prepare_split_single(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) : Optional[int] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards)) all_shard_lengths.extend(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = total_num_examples __lowerCAmelCase : Union[str, Any] = total_num_bytes # should rename everything at the end logger.debug(F"""Renaming {total_shards} shards.""") if total_shards > 1: __lowerCAmelCase : Tuple = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __lowerCAmelCase : Optional[Any] = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Tuple , ): rename( _SCREAMING_SNAKE_CASE , fpath.replace("SSSSS" , F"""{shard_id:05d}""").replace("TTTTT" , F"""{task_id:05d}""") , fpath.replace("TTTTT-SSSSS" , F"""{global_shard_id:05d}""").replace("NNNNN" , F"""{total_shards:05d}""") , ) __lowerCAmelCase : str = [] __lowerCAmelCase : Optional[int] = 0 for i in range(len(_SCREAMING_SNAKE_CASE)): __lowerCAmelCase , __lowerCAmelCase : Dict = task_id_and_num_shards[i] for shard_id in range(_SCREAMING_SNAKE_CASE): args.append([task_id, shard_id, global_shard_id]) global_shard_id += 1 self._spark.sparkContext.parallelize(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE)).map(lambda _SCREAMING_SNAKE_CASE: _rename_shard(*_SCREAMING_SNAKE_CASE)).collect() else: # don't use any pattern __lowerCAmelCase : Any = 0 __lowerCAmelCase : List[str] = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS" , F"""{shard_id:05d}""").replace("TTTTT" , F"""{task_id:05d}""") , fpath.replace(_SCREAMING_SNAKE_CASE , "") , ) def _SCREAMING_SNAKE_CASE ( self: str , _SCREAMING_SNAKE_CASE: List[Any] , ) -> SparkExamplesIterable: """simple docstring""" return SparkExamplesIterable(self.df)
293
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
0
'''simple docstring''' def __lowerCAmelCase ( a_ , a_ , a_ ) -> Union[str, Any]: '''simple docstring''' if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(_UpperCAmelCase , n - 1 , _UpperCAmelCase ) * a) % mod else: SCREAMING_SNAKE_CASE : List[Any] = binary_exponentiation(_UpperCAmelCase , n / 2 , _UpperCAmelCase ) return (b * b) % mod # a prime number _lowerCAmelCase :str = 701 _lowerCAmelCase :Union[str, Any] = 1_000_000_000 _lowerCAmelCase :List[str] = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
251
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=a , **a) elif isinstance(a , a): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.') return self.tokenizer(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''') if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCAmelCase ( A__ ): A__ : Dict = ['''image_processor''', '''tokenizer'''] A__ : Optional[Any] = '''AutoImageProcessor''' A__ : List[Any] = '''AutoTokenizer''' def __init__(self : List[Any] , snake_case__ : Union[str, Any] , snake_case__ : str ) -> Any: '''simple docstring''' super().__init__(snake_case__ , snake_case__ ) snake_case : Optional[int] = self.image_processor def __call__(self : Dict , snake_case__ : Any=None , snake_case__ : int=None , snake_case__ : Any=None , **snake_case__ : List[Any] ) -> Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: snake_case : List[Any] = self.tokenizer(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if images is not None: snake_case : Optional[int] = self.image_processor(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if text is not None and images is not None: snake_case : Tuple = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**snake_case__ ) , tensor_type=snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] , *snake_case__ : Optional[int] , **snake_case__ : Tuple ) -> Tuple: '''simple docstring''' return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] , *snake_case__ : Union[str, Any] , **snake_case__ : Optional[int] ) -> List[Any]: '''simple docstring''' return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def _SCREAMING_SNAKE_CASE (self : Dict ) -> List[str]: '''simple docstring''' return ["input_ids", "attention_mask", "pixel_values"]
204
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __UpperCAmelCase : List[str] = '▁' __UpperCAmelCase : str = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class _snake_case ( A__ , unittest.TestCase ): _A = BigBirdTokenizer _A = BigBirdTokenizerFast _A = True _A = True def lowerCAmelCase_ ( self ) -> Optional[Any]: super().setUp() snake_case__ :int = self.tokenizer_class(UpperCamelCase ,keep_accents=UpperCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase_ ( self ) -> Dict: snake_case__ :List[Any] = "<s>" snake_case__ :str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase ) ,UpperCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase ) ,UpperCamelCase ) def lowerCAmelCase_ ( self ) -> List[str]: snake_case__ :Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,"<unk>" ) self.assertEqual(vocab_keys[1] ,"<s>" ) self.assertEqual(vocab_keys[-1] ,"[MASK]" ) self.assertEqual(len(UpperCamelCase ) ,1_004 ) def lowerCAmelCase_ ( self ) -> Optional[Any]: self.assertEqual(self.get_tokenizer().vocab_size ,1_000 ) def lowerCAmelCase_ ( self ) -> str: if not self.test_rust_tokenizer: return snake_case__ :int = self.get_tokenizer() snake_case__ :Tuple = self.get_rust_tokenizer() snake_case__ :Optional[int] = "I was born in 92000, and this is falsé." snake_case__ :int = tokenizer.tokenize(UpperCamelCase ) snake_case__ :str = rust_tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase ,UpperCamelCase ) snake_case__ :Optional[int] = tokenizer.encode(UpperCamelCase ,add_special_tokens=UpperCamelCase ) snake_case__ :Optional[int] = rust_tokenizer.encode(UpperCamelCase ,add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase ,UpperCamelCase ) snake_case__ :Optional[int] = self.get_rust_tokenizer() snake_case__ :List[str] = tokenizer.encode(UpperCamelCase ) snake_case__ :List[str] = rust_tokenizer.encode(UpperCamelCase ) self.assertListEqual(UpperCamelCase ,UpperCamelCase ) def lowerCAmelCase_ ( self ) -> str: snake_case__ :Union[str, Any] = BigBirdTokenizer(UpperCamelCase ,keep_accents=UpperCamelCase ) snake_case__ :int = tokenizer.tokenize("This is a test" ) self.assertListEqual(UpperCamelCase ,["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCamelCase ) ,[285, 46, 10, 170, 382] ,) snake_case__ :List[str] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( UpperCamelCase ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] ,) snake_case__ :List[Any] = tokenizer.convert_tokens_to_ids(UpperCamelCase ) self.assertListEqual( UpperCamelCase ,[8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ,) snake_case__ :Optional[int] = tokenizer.convert_ids_to_tokens(UpperCamelCase ) self.assertListEqual( UpperCamelCase ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] ,) @cached_property def lowerCAmelCase_ ( self ) -> Union[str, Any]: return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def lowerCAmelCase_ ( self ) -> Union[str, Any]: snake_case__ :int = "Hello World!" snake_case__ :List[Any] = [65, 18_536, 2_260, 101, 66] self.assertListEqual(UpperCamelCase ,self.big_tokenizer.encode(UpperCamelCase ) ) @slow def lowerCAmelCase_ ( self ) -> Optional[int]: snake_case__ :List[str] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) # fmt: off snake_case__ :Union[str, Any] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231 # fmt: on self.assertListEqual(UpperCamelCase ,self.big_tokenizer.encode(UpperCamelCase ) ) @require_torch @slow def lowerCAmelCase_ ( self ) -> Any: import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence snake_case__ :Dict = list(self.big_tokenizer.get_vocab().keys() )[:10] snake_case__ :Tuple = " ".join(UpperCamelCase ) snake_case__ :List[Any] = self.big_tokenizer.encode_plus(UpperCamelCase ,return_tensors="pt" ,return_token_type_ids=UpperCamelCase ) snake_case__ :Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] ,return_tensors="pt" ,return_token_type_ids=UpperCamelCase ) snake_case__ :Any = BigBirdConfig(attention_type="original_full" ) snake_case__ :Optional[int] = BigBirdModel(UpperCamelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**UpperCamelCase ) model(**UpperCamelCase ) @slow def lowerCAmelCase_ ( self ) -> Union[str, Any]: snake_case__ :Union[str, Any] = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) snake_case__ :Optional[int] = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def lowerCAmelCase_ ( self ) -> Dict: # fmt: off snake_case__ :Dict = {"input_ids": [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase ,model_name="google/bigbird-roberta-base" ,revision="215c99f1600e06f83acce68422f2035b2b5c3510" ,)
241
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
0
"""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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase__ = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure)
110
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def __UpperCAmelCase ( a_ , a_=False): snake_case_ = [] for i in range(config.num_hidden_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''module.blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''')) rename_keys.append((f'''module.blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''')) rename_keys.append( (f'''module.blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''')) rename_keys.append((f'''module.blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''')) rename_keys.append((f'''module.blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''')) rename_keys.append((f'''module.blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''')) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''')) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''')) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''')) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''')) # projection layer + position embeddings rename_keys.extend( [ ('module.cls_token', 'vit.embeddings.cls_token'), ('module.patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'), ('module.patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'), ('module.pos_embed', 'vit.embeddings.position_embeddings'), ]) if base_model: # layernorm + pooler rename_keys.extend( [ ('module.norm.weight', 'layernorm.weight'), ('module.norm.bias', 'layernorm.bias'), ]) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith('vit') else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('norm.weight', 'vit.layernorm.weight'), ('norm.bias', 'vit.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ]) return rename_keys def __UpperCAmelCase ( a_ , a_ , a_=False): for i in range(config.num_hidden_layers): if base_model: snake_case_ = '' else: snake_case_ = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f'''module.blocks.{i}.attn.qkv.weight''') snake_case_ = state_dict.pop(f'''module.blocks.{i}.attn.qkv.bias''') # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def __UpperCAmelCase ( a_): snake_case_ = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def __UpperCAmelCase ( a_): # projection head is used in the self-supervised pre-training in MSN, # for downstream task it's not needed. snake_case_ = [ 'module.fc.fc1.weight', 'module.fc.fc1.bias', 'module.fc.bn1.weight', 'module.fc.bn1.bias', 'module.fc.bn1.running_mean', 'module.fc.bn1.running_var', 'module.fc.bn1.num_batches_tracked', 'module.fc.fc2.weight', 'module.fc.fc2.bias', 'module.fc.bn2.weight', 'module.fc.bn2.bias', 'module.fc.bn2.running_mean', 'module.fc.bn2.running_var', 'module.fc.bn2.num_batches_tracked', 'module.fc.fc3.weight', 'module.fc.fc3.bias', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def __UpperCAmelCase ( a_ , a_ , a_): snake_case_ = dct.pop(_UpperCAmelCase) snake_case_ = val def __UpperCAmelCase ( a_ , a_): snake_case_ = ViTMSNConfig() snake_case_ = 10_00 snake_case_ = 'datasets/huggingface/label-files' snake_case_ = 'imagenet-1k-id2label.json' snake_case_ = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) , 'r')) snake_case_ = {int(_UpperCAmelCase): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: snake_case_ = 3_84 snake_case_ = 15_36 snake_case_ = 6 elif "l16" in checkpoint_url: snake_case_ = 10_24 snake_case_ = 40_96 snake_case_ = 24 snake_case_ = 16 snake_case_ = 0.1 elif "b4" in checkpoint_url: snake_case_ = 4 elif "l7" in checkpoint_url: snake_case_ = 7 snake_case_ = 10_24 snake_case_ = 40_96 snake_case_ = 24 snake_case_ = 16 snake_case_ = 0.1 snake_case_ = ViTMSNModel(_UpperCAmelCase) snake_case_ = torch.hub.load_state_dict_from_url(_UpperCAmelCase , map_location='cpu')['target_encoder'] snake_case_ = ViTImageProcessor(size=config.image_size) remove_projection_head(_UpperCAmelCase) snake_case_ = create_rename_keys(_UpperCAmelCase , base_model=_UpperCAmelCase) for src, dest in rename_keys: rename_key(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) read_in_q_k_v(_UpperCAmelCase , _UpperCAmelCase , base_model=_UpperCAmelCase) model.load_state_dict(_UpperCAmelCase) model.eval() snake_case_ = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case_ = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase).raw) snake_case_ = ViTImageProcessor( size=config.image_size , image_mean=_UpperCAmelCase , image_std=_UpperCAmelCase) snake_case_ = image_processor(images=_UpperCAmelCase , return_tensors='pt') # forward pass torch.manual_seed(2) snake_case_ = model(**_UpperCAmelCase) snake_case_ = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: snake_case_ = torch.tensor([[-1.09_15, -1.48_76, -1.18_09]]) elif "b16" in checkpoint_url: snake_case_ = torch.tensor([[14.28_89, -18.90_45, 11.72_81]]) elif "l16" in checkpoint_url: snake_case_ = torch.tensor([[41.50_28, -22.86_81, 45.64_75]]) elif "b4" in checkpoint_url: snake_case_ = torch.tensor([[-4.38_68, 5.29_32, -0.41_37]]) else: snake_case_ = torch.tensor([[-0.17_92, -0.64_65, 2.42_63]]) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , _UpperCAmelCase , atol=1E-4) print(f'''Saving model to {pytorch_dump_folder_path}''') model.save_pretrained(_UpperCAmelCase) print(f'''Saving image processor to {pytorch_dump_folder_path}''') image_processor.save_pretrained(_UpperCAmelCase) if __name__ == "__main__": lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar", type=str, help="URL of the checkpoint you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) lowercase = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
198
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json', } class __lowercase ( A__): """simple docstring""" _A : Any = '''git_vision_model''' def __init__(self , lowercase__=7_68 , lowercase__=30_72 , lowercase__=12 , lowercase__=12 , lowercase__=3 , lowercase__=2_24 , lowercase__=16 , lowercase__="quick_gelu" , lowercase__=1e-5 , lowercase__=0.0 , lowercase__=0.02 , **lowercase__ , ): super().__init__(**lowercase__ ) snake_case_ : List[str] = hidden_size snake_case_ : Tuple = intermediate_size snake_case_ : List[str] = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : Optional[Any] = num_channels snake_case_ : int = patch_size snake_case_ : List[str] = image_size snake_case_ : List[str] = initializer_range snake_case_ : Optional[Any] = attention_dropout snake_case_ : Tuple = layer_norm_eps snake_case_ : Tuple = hidden_act @classmethod def __UpperCamelCase (cls , lowercase__ , **lowercase__ ): cls._set_token_in_kwargs(lowercase__ ) snake_case_ , snake_case_ : str = cls.get_config_dict(lowercase__ , **lowercase__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": snake_case_ : int = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(lowercase__ , **lowercase__ ) class __lowercase ( A__): """simple docstring""" _A : List[Any] = '''git''' def __init__(self , lowercase__=None , lowercase__=3_05_22 , lowercase__=7_68 , lowercase__=6 , lowercase__=12 , lowercase__=30_72 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=10_24 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=0 , lowercase__="absolute" , lowercase__=True , lowercase__=False , lowercase__=1_01 , lowercase__=1_02 , lowercase__=None , **lowercase__ , ): super().__init__(bos_token_id=lowercase__ , eos_token_id=lowercase__ , pad_token_id=lowercase__ , **lowercase__ ) if vision_config is None: snake_case_ : List[str] = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) snake_case_ : Optional[int] = GitVisionConfig(**lowercase__ ) snake_case_ : Dict = vocab_size snake_case_ : int = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Optional[Any] = num_attention_heads snake_case_ : Tuple = hidden_act snake_case_ : List[str] = intermediate_size snake_case_ : Optional[Any] = hidden_dropout_prob snake_case_ : Any = attention_probs_dropout_prob snake_case_ : Any = max_position_embeddings snake_case_ : List[Any] = initializer_range snake_case_ : str = layer_norm_eps snake_case_ : Tuple = position_embedding_type snake_case_ : Dict = use_cache snake_case_ : Union[str, Any] = tie_word_embeddings snake_case_ : List[str] = num_image_with_embedding snake_case_ : Dict = bos_token_id snake_case_ : List[str] = eos_token_id def __UpperCamelCase (self ): snake_case_ : Any = copy.deepcopy(self.__dict__ ) snake_case_ : Any = self.vision_config.to_dict() snake_case_ : List[Any] = self.__class__.model_type return output
480
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __snake_case = '2.13.1' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip __snake_case = concatenate_datasets __snake_case = DownloadConfig __snake_case = DownloadManager __snake_case = DownloadMode __snake_case = DownloadConfig __snake_case = DownloadMode __snake_case = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
386
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
0
import math def SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: """simple docstring""" A__ = [True] * n A__ = False A__ = False A__ = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): A__ = i * 2 while index < n: A__ = False A__ = index + i A__ = [2] for i in range(3 , _UpperCAmelCase , 2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def SCREAMING_SNAKE_CASE ( lowercase_ = 999_966_663_333 ) -> Any: """simple docstring""" A__ = math.floor(math.sqrt(_UpperCAmelCase ) ) + 100 A__ = prime_sieve(_UpperCAmelCase ) A__ = 0 A__ = 0 A__ = primes[prime_index] while (last_prime**2) <= limit: A__ = primes[prime_index + 1] A__ = last_prime**2 A__ = next_prime**2 # Get numbers divisible by lps(current) A__ = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A__ = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A__ = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A__ = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
87
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
0
"""simple docstring""" def __a ( a ): """simple docstring""" if not numbers: return 0 if not isinstance(_UpperCAmelCase, (list, tuple) ) or not all( isinstance(_UpperCAmelCase, _UpperCAmelCase ) for number in numbers ): raise ValueError("numbers must be an iterable of integers" ) _a = _a = _a = numbers[0] for i in range(1, len(_UpperCAmelCase ) ): # update the maximum and minimum subarray products _a = numbers[i] if number < 0: _a , _a = min_till_now, max_till_now _a = max(_UpperCAmelCase, max_till_now * number ) _a = min(_UpperCAmelCase, min_till_now * number ) # update the maximum product found till now _a = max(_UpperCAmelCase, _UpperCAmelCase ) return max_prod
388
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor UpperCamelCase_ : Dict = logging.get_logger(__name__) class lowerCamelCase__ ( A__ ): """simple docstring""" def __init__( self : int ,*a__ : str ,**a__ : int ): warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." ,a__ ,) super().__init__(*a__ ,**a__ )
331
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : 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=37 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
0
"""simple docstring""" import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowercase ( __snake_case ,__snake_case=False ) -> List[Any]: try: __lowerCAmelCase : Optional[int] = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __lowerCAmelCase : List[Any] = default else: # KEY is set, convert it to True or False. try: __lowerCAmelCase : List[Any] = strtobool(_UpperCAmelCase ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"""If set, {key} must be yes or no.""" ) return _value __snake_case : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) __snake_case : int = parse_flag_from_env('RUN_REMOTE', default=False) __snake_case : List[str] = parse_flag_from_env('RUN_LOCAL', default=True) __snake_case : Dict = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression __snake_case : Tuple = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') __snake_case : Dict = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') __snake_case : Optional[int] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio __snake_case : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam __snake_case : int = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility __snake_case : Dict = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows __snake_case : Optional[int] = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowercase ( __snake_case ) -> List[Any]: try: import faiss # noqa except ImportError: __lowerCAmelCase : Union[str, Any] = unittest.skip("test requires faiss" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> List[str]: try: import regex # noqa except ImportError: __lowerCAmelCase : List[Any] = unittest.skip("test requires regex" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> Dict: try: import elasticsearch # noqa except ImportError: __lowerCAmelCase : Tuple = unittest.skip("test requires elasticsearch" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> Any: try: import sqlalchemy # noqa except ImportError: __lowerCAmelCase : Tuple = unittest.skip("test requires sqlalchemy" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> List[str]: if not config.TORCH_AVAILABLE: __lowerCAmelCase : List[Any] = unittest.skip("test requires PyTorch" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> Optional[int]: if not config.TF_AVAILABLE: __lowerCAmelCase : Any = unittest.skip("test requires TensorFlow" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> Tuple: if not config.JAX_AVAILABLE: __lowerCAmelCase : Tuple = unittest.skip("test requires JAX" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> int: if not config.PIL_AVAILABLE: __lowerCAmelCase : Any = unittest.skip("test requires Pillow" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> Union[str, Any]: try: import transformers # noqa F401 except ImportError: return unittest.skip("test requires transformers" )(_UpperCAmelCase ) else: return test_case def _lowercase ( __snake_case ) -> Any: try: import tiktoken # noqa F401 except ImportError: return unittest.skip("test requires tiktoken" )(_UpperCAmelCase ) else: return test_case def _lowercase ( __snake_case ) -> Optional[Any]: try: import spacy # noqa F401 except ImportError: return unittest.skip("test requires spacy" )(_UpperCAmelCase ) else: return test_case def _lowercase ( __snake_case ) -> List[str]: def _require_spacy_model(__snake_case ): try: import spacy # noqa F401 spacy.load(_UpperCAmelCase ) except ImportError: return unittest.skip("test requires spacy" )(_UpperCAmelCase ) except OSError: return unittest.skip("test requires spacy model \'{}\'".format(_UpperCAmelCase ) )(_UpperCAmelCase ) else: return test_case return _require_spacy_model def _lowercase ( __snake_case ) -> Optional[int]: try: import pyspark # noqa F401 except ImportError: return unittest.skip("test requires pyspark" )(_UpperCAmelCase ) else: return test_case def _lowercase ( __snake_case ) -> int: try: import joblibspark # noqa F401 except ImportError: return unittest.skip("test requires joblibspark" )(_UpperCAmelCase ) else: return test_case def _lowercase ( __snake_case ) -> int: if not _run_slow_tests or _run_slow_tests == 0: __lowerCAmelCase : Tuple = unittest.skip("test is slow" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> Union[str, Any]: if not _run_local_tests or _run_local_tests == 0: __lowerCAmelCase : List[Any] = unittest.skip("test is local" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> str: if not _run_packaged_tests or _run_packaged_tests == 0: __lowerCAmelCase : Any = unittest.skip("test is packaged" )(_UpperCAmelCase ) return test_case def _lowercase ( __snake_case ) -> List[str]: if not _run_remote_tests or _run_remote_tests == 0: __lowerCAmelCase : str = unittest.skip("test requires remote" )(_UpperCAmelCase ) return test_case def _lowercase ( *__snake_case ) -> List[Any]: def decorate(cls ): for name, fn in cls.__dict__.items(): if callable(_UpperCAmelCase ) and name.startswith("test" ): for decorator in decorators: __lowerCAmelCase : Optional[int] = decorator(_UpperCAmelCase ) setattr(cls ,_UpperCAmelCase ,_UpperCAmelCase ) return cls return decorate class A__ ( A__ ): '''simple docstring''' pass class A__ ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 2 @contextmanager def _lowercase ( __snake_case=OfflineSimulationMode.CONNECTION_FAILS ,__snake_case=1e-1_6 ) -> List[str]: __lowerCAmelCase : Tuple = requests.Session().request def timeout_request(__snake_case ,__snake_case ,__snake_case ,**__snake_case ): # Change the url to an invalid url so that the connection hangs __lowerCAmelCase : str = "https://10.255.255.1" if kwargs.get("timeout" ) is None: raise RequestWouldHangIndefinitelyError( F"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout.""" ) __lowerCAmelCase : Tuple = timeout try: return online_request(_UpperCAmelCase ,_UpperCAmelCase ,**_UpperCAmelCase ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __lowerCAmelCase : Tuple = url __lowerCAmelCase : Optional[int] = e.args[0] __lowerCAmelCase : List[str] = (max_retry_error.args[0].replace("10.255.255.1" ,F"""OfflineMock[{url}]""" ),) __lowerCAmelCase : Optional[int] = (max_retry_error,) raise def raise_connection_error(__snake_case ,__snake_case ,**__snake_case ): raise requests.ConnectionError("Offline mode is enabled." ,request=_UpperCAmelCase ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("requests.Session.send" ,_UpperCAmelCase ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("requests.Session.request" ,_UpperCAmelCase ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("datasets.config.HF_DATASETS_OFFLINE" ,_UpperCAmelCase ): yield else: raise ValueError("Please use a value from the OfflineSimulationMode enum." ) @contextmanager def _lowercase ( *__snake_case ,**__snake_case ) -> str: __lowerCAmelCase : Optional[Any] = str(Path().resolve() ) with tempfile.TemporaryDirectory(*_UpperCAmelCase ,**_UpperCAmelCase ) as tmp_dir: try: os.chdir(_UpperCAmelCase ) yield finally: os.chdir(_UpperCAmelCase ) @contextmanager def _lowercase ( ) -> str: import gc gc.collect() __lowerCAmelCase : str = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowercase ( ) -> str: import gc gc.collect() __lowerCAmelCase : Tuple = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowercase ( __snake_case ,__snake_case ) -> Union[str, Any]: return deepcopy(_UpperCAmelCase ).integers(0 ,100 ,10 ).tolist() == deepcopy(_UpperCAmelCase ).integers(0 ,100 ,10 ).tolist() def _lowercase ( __snake_case ) -> Optional[Any]: import decorator from requests.exceptions import HTTPError def _wrapper(__snake_case ,*__snake_case ,**__snake_case ): try: return func(*_UpperCAmelCase ,**_UpperCAmelCase ) except HTTPError as err: if str(_UpperCAmelCase ).startswith("500" ) or str(_UpperCAmelCase ).startswith("502" ): pytest.xfail(str(_UpperCAmelCase ) ) raise err return decorator.decorator(_wrapper ,_UpperCAmelCase ) class A__ : '''simple docstring''' def __init__( self: Any , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> List[str]: """simple docstring""" __lowerCAmelCase : List[str] = returncode __lowerCAmelCase : List[str] = stdout __lowerCAmelCase : List[str] = stderr async def _lowercase ( __snake_case ,__snake_case ) -> Optional[int]: while True: __lowerCAmelCase : Optional[Any] = await stream.readline() if line: callback(_UpperCAmelCase ) else: break async def _lowercase ( __snake_case ,__snake_case=None ,__snake_case=None ,__snake_case=None ,__snake_case=False ,__snake_case=False ) -> Dict: if echo: print("\nRunning: " ," ".join(_UpperCAmelCase ) ) __lowerCAmelCase : Tuple = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=_UpperCAmelCase ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=_UpperCAmelCase ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __lowerCAmelCase : Tuple = [] __lowerCAmelCase : Any = [] def tee(__snake_case ,__snake_case ,__snake_case ,__snake_case="" ): __lowerCAmelCase : Dict = line.decode("utf-8" ).rstrip() sink.append(_UpperCAmelCase ) if not quiet: print(_UpperCAmelCase ,_UpperCAmelCase ,file=_UpperCAmelCase ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __snake_case : tee(_UpperCAmelCase ,_UpperCAmelCase ,sys.stdout ,label="stdout:" ) ), _read_stream(p.stderr ,lambda __snake_case : tee(_UpperCAmelCase ,_UpperCAmelCase ,sys.stderr ,label="stderr:" ) ), ] ,timeout=_UpperCAmelCase ,) return _RunOutput(await p.wait() ,_UpperCAmelCase ,_UpperCAmelCase ) def _lowercase ( __snake_case ,__snake_case=None ,__snake_case=None ,__snake_case=180 ,__snake_case=False ,__snake_case=True ) -> Any: __lowerCAmelCase : Any = asyncio.get_event_loop() __lowerCAmelCase : Dict = loop.run_until_complete( _stream_subprocess(_UpperCAmelCase ,env=_UpperCAmelCase ,stdin=_UpperCAmelCase ,timeout=_UpperCAmelCase ,quiet=_UpperCAmelCase ,echo=_UpperCAmelCase ) ) __lowerCAmelCase : Union[str, Any] = " ".join(_UpperCAmelCase ) if result.returncode > 0: __lowerCAmelCase : List[Any] = "\n".join(result.stderr ) raise RuntimeError( F"""\'{cmd_str}\' failed with returncode {result.returncode}\n\n""" F"""The combined stderr from workers follows:\n{stderr}""" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(F"""\'{cmd_str}\' produced no output.""" ) return result def _lowercase ( ) -> Optional[int]: __lowerCAmelCase : Dict = os.environ.get("PYTEST_XDIST_WORKER" ,"gw0" ) __lowerCAmelCase : int = re.sub(r"^gw" ,"" ,_UpperCAmelCase ,0 ,re.M ) return int(_UpperCAmelCase ) def _lowercase ( ) -> Union[str, Any]: __lowerCAmelCase : List[str] = 29_500 __lowerCAmelCase : Tuple = pytest_xdist_worker_id() return port + uniq_delta
293
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
'''simple docstring''' import math import flax.linen as nn import jax.numpy as jnp def __lowerCAmelCase ( a_ , a_ , a_ = 1 , a_ = 1 , a_ = 1.0e4 , a_ = False , a_ = 1.0 , ) -> Union[str, Any]: '''simple docstring''' assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, f"""Embedding dimension {embedding_dim} should be even""" SCREAMING_SNAKE_CASE : int = float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE : List[Any] = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE : List[str] = min_timescale * jnp.exp(jnp.arange(_UpperCAmelCase , dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE : Tuple = jnp.expand_dims(_UpperCAmelCase , 1 ) * jnp.expand_dims(_UpperCAmelCase , 0 ) # scale embeddings SCREAMING_SNAKE_CASE : Any = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.concatenate([jnp.cos(_UpperCAmelCase ), jnp.sin(_UpperCAmelCase )] , axis=1 ) else: SCREAMING_SNAKE_CASE : int = jnp.concatenate([jnp.sin(_UpperCAmelCase ), jnp.cos(_UpperCAmelCase )] , axis=1 ) SCREAMING_SNAKE_CASE : Optional[int] = jnp.reshape(_UpperCAmelCase , [jnp.shape(_UpperCAmelCase )[0], embedding_dim] ) return signal class UpperCAmelCase ( nn.Module ): '''simple docstring''' snake_case__ : int = 3_2 snake_case__ : jnp.dtype = jnp.floataa @nn.compact def __call__( self , lowercase__ ) -> int: SCREAMING_SNAKE_CASE : Tuple = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(lowercase__ ) SCREAMING_SNAKE_CASE : List[str] = nn.silu(lowercase__ ) SCREAMING_SNAKE_CASE : int = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(lowercase__ ) return temb class UpperCAmelCase ( nn.Module ): '''simple docstring''' snake_case__ : int = 3_2 snake_case__ : bool = False snake_case__ : float = 1 @nn.compact def __call__( self , lowercase__ ) -> str: return get_sinusoidal_embeddings( lowercase__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
251
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) 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.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __lowerCamelCase = logging.getLogger(__name__) __lowerCamelCase = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __lowerCamelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCAmelCase : A__ : Optional[str] = field( default=A__ ,metadata={ "help": ( "The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch." ) } ,) A__ : Optional[str] = field( default=A__ ,metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(A__ )} ,) A__ : Optional[str] = field( default=A__ ,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" ) } ,) A__ : Optional[str] = field( default=A__ ,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) A__ : Optional[str] = field( default=A__ ,metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) A__ : Optional[str] = field( default=A__ ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,) A__ : bool = field( default=A__ ,metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} ,) A__ : str = field( default="main" ,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} ,) A__ : bool = field( default=A__ ,metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } ,) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> List[str]: '''simple docstring''' if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can\'t be used in combination with --config_name or --model_name_or_path" ) @dataclass class UpperCAmelCase : A__ : Optional[str] = field( default=A__ ,metadata={"help": "The name of the dataset to use (via the datasets library)."} ) A__ : Optional[str] = field( default=A__ ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) A__ : Optional[str] = field(default=A__ ,metadata={"help": "The input training data file (a text file)."} ) A__ : Optional[str] = field( default=A__ ,metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} ,) A__ : Optional[str] = field( default=A__ ,metadata={"help": "An optional input train ref data file for whole word masking in Chinese."} ,) A__ : Optional[str] = field( default=A__ ,metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."} ,) A__ : bool = field( default=A__ ,metadata={"help": "Overwrite the cached training and evaluation sets"} ) A__ : Optional[int] = field( default=5 ,metadata={ "help": "The percentage of the train set used as validation set in case there\'s no validation split" } ,) A__ : Optional[int] = field( default=A__ ,metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated. Default to the max input length of the model." ) } ,) A__ : Optional[int] = field( default=A__ ,metadata={"help": "The number of processes to use for the preprocessing."} ,) A__ : float = field( default=0.15 ,metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} ) A__ : bool = field( default=A__ ,metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } ,) def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> Optional[int]: '''simple docstring''' if self.train_file is not None: snake_case : str = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: snake_case : Dict = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def UpperCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] ): with open(_UpperCAmelCase , "r" , encoding="utf-8" ) as f: snake_case : int = [json.loads(_UpperCAmelCase ) for line in f.read().splitlines() if (len(_UpperCAmelCase ) > 0 and not line.isspace())] assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ) snake_case : Any = {c: dataset[c] for c in dataset.column_names} snake_case : List[Any] = refs return Dataset.from_dict(_UpperCAmelCase ) def UpperCamelCase ( ): # 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. snake_case : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case , snake_case , snake_case : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case , snake_case , snake_case : str = parser.parse_args_into_dataclasses() # Detecting last checkpoint. snake_case : List[str] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case : List[Any] = 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: 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." ) # 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 )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # 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}""" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , _UpperCAmelCase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case : Dict = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): snake_case : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""train[:{data_args.validation_split_percentage}%]""" , ) snake_case : Tuple = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""train[{data_args.validation_split_percentage}%:]""" , ) else: snake_case : str = {} if data_args.train_file is not None: snake_case : List[str] = data_args.train_file if data_args.validation_file is not None: snake_case : Union[str, Any] = data_args.validation_file snake_case : Union[str, Any] = data_args.train_file.split("." )[-1] if extension == "txt": snake_case : List[Any] = "text" snake_case : List[Any] = load_dataset(_UpperCAmelCase , data_files=_UpperCAmelCase ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case : Any = { "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: snake_case : Optional[int] = AutoConfig.from_pretrained(model_args.config_name , **_UpperCAmelCase ) elif model_args.model_name_or_path: snake_case : str = AutoConfig.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase ) else: snake_case : Dict = CONFIG_MAPPING[model_args.model_type]() 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}""" ) snake_case : str = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: snake_case : Tuple = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **_UpperCAmelCase ) elif model_args.model_name_or_path: snake_case : Tuple = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase ) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) if model_args.model_name_or_path: snake_case : Tuple = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=_UpperCAmelCase , cache_dir=model_args.cache_dir , 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" ) snake_case : Tuple = AutoModelForMaskedLM.from_config(_UpperCAmelCase ) model.resize_token_embeddings(len(_UpperCAmelCase ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: snake_case : List[str] = datasets["train"].column_names else: snake_case : Optional[Any] = datasets["validation"].column_names snake_case : str = "text" if "text" in column_names else column_names[0] snake_case : List[Any] = "max_length" if data_args.pad_to_max_length else False def tokenize_function(__lowerCamelCase : str ): # Remove empty lines snake_case : Optional[Any] = [line for line in examples["text"] if len(_UpperCAmelCase ) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=data_args.max_seq_length ) snake_case : Tuple = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: snake_case : Any = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: snake_case : Tuple = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer snake_case : Tuple = data_args.train_ref_file or data_args.validation_ref_file if has_ref: snake_case : Optional[int] = False # Data collator # This one will take care of randomly masking the tokens. snake_case : Dict = DataCollatorForWholeWordMask(tokenizer=_UpperCAmelCase , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer snake_case : Union[str, Any] = Trainer( model=_UpperCAmelCase , args=_UpperCAmelCase , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=_UpperCAmelCase , data_collator=_UpperCAmelCase , ) # Training if training_args.do_train: if last_checkpoint is not None: snake_case : Optional[Any] = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): snake_case : Union[str, Any] = model_args.model_name_or_path else: snake_case : str = None snake_case : int = trainer.train(resume_from_checkpoint=_UpperCAmelCase ) trainer.save_model() # Saves the tokenizer too for easy upload snake_case : str = os.path.join(training_args.output_dir , "train_results.txt" ) if trainer.is_world_process_zero(): with open(_UpperCAmelCase , "w" ) as writer: logger.info("***** Train results *****" ) for key, value in sorted(train_result.metrics.items() ): logger.info(f""" {key} = {value}""" ) writer.write(f"""{key} = {value}\n""" ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # Evaluation snake_case : Any = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) snake_case : Any = trainer.evaluate() snake_case : Optional[Any] = math.exp(eval_output["eval_loss"] ) snake_case : Tuple = perplexity snake_case : str = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt" ) if trainer.is_world_process_zero(): with open(_UpperCAmelCase , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in sorted(results.items() ): logger.info(f""" {key} = {value}""" ) writer.write(f"""{key} = {value}\n""" ) return results def UpperCamelCase ( __lowerCamelCase : Dict ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
204
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _snake_case ( A__ , A__ , A__ ): @register_to_config def __init__( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = False ,) -> int: super().__init__() snake_case__ :Optional[Any] = nn.Embedding(UpperCamelCase ,UpperCamelCase ) snake_case__ :Any = nn.Embedding(UpperCamelCase ,UpperCamelCase ) snake_case__ :str = False snake_case__ :Union[str, Any] = nn.Dropout(p=UpperCamelCase ) snake_case__ :Any = TaConfig( vocab_size=UpperCamelCase ,d_model=UpperCamelCase ,num_heads=UpperCamelCase ,d_kv=UpperCamelCase ,d_ff=UpperCamelCase ,dropout_rate=UpperCamelCase ,feed_forward_proj=UpperCamelCase ,is_decoder=UpperCamelCase ,is_encoder_decoder=UpperCamelCase ,) snake_case__ :Union[str, Any] = nn.ModuleList() for lyr_num in range(UpperCamelCase ): snake_case__ :Any = TaBlock(UpperCamelCase ) self.encoders.append(UpperCamelCase ) snake_case__ :Optional[int] = TaLayerNorm(UpperCamelCase ) snake_case__ :int = nn.Dropout(p=UpperCamelCase ) def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ) -> Optional[int]: snake_case__ :List[str] = self.token_embedder(UpperCamelCase ) snake_case__ :Any = encoder_input_tokens.shape[1] snake_case__ :Union[str, Any] = torch.arange(UpperCamelCase ,device=encoder_input_tokens.device ) x += self.position_encoding(UpperCamelCase ) snake_case__ :Union[str, Any] = self.dropout_pre(UpperCamelCase ) # inverted the attention mask snake_case__ :Tuple = encoder_input_tokens.size() snake_case__ :Any = self.get_extended_attention_mask(UpperCamelCase ,UpperCamelCase ) for lyr in self.encoders: snake_case__ :Dict = lyr(UpperCamelCase ,UpperCamelCase )[0] snake_case__ :Dict = self.layer_norm(UpperCamelCase ) return self.dropout_post(UpperCamelCase ), encoder_inputs_mask
241
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
"""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 a ( A__ ): UpperCamelCase : Any = ['''image_processor''', '''tokenizer'''] UpperCamelCase : Tuple = '''LayoutLMv3ImageProcessor''' UpperCamelCase : int = ('''LayoutLMv3Tokenizer''', '''LayoutLMv3TokenizerFast''') def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , **UpperCamelCase_ ): UpperCAmelCase__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , UpperCamelCase_ , ) UpperCAmelCase__ : Union[str, Any] = kwargs.pop('feature_extractor' ) UpperCAmelCase__ : str = 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__(UpperCamelCase_ , UpperCamelCase_ ) def __call__( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = True , UpperCamelCase_ = False , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = 0 , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = True , UpperCamelCase_ = None , **UpperCamelCase_ , ): # 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 UpperCAmelCase__ : Union[str, Any] = self.image_processor(images=UpperCamelCase_ , return_tensors=UpperCamelCase_ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCAmelCase__ : str = [text] # add batch dimension (as the image processor always adds a batch dimension) UpperCAmelCase__ : Tuple = features['words'] UpperCAmelCase__ : Optional[Any] = 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=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ , stride=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , return_overflowing_tokens=UpperCamelCase_ , return_special_tokens_mask=UpperCamelCase_ , return_offsets_mapping=UpperCamelCase_ , return_length=UpperCamelCase_ , verbose=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ , ) # add pixel values UpperCAmelCase__ : int = features.pop('pixel_values' ) if return_overflowing_tokens is True: UpperCAmelCase__ : Optional[int] = self.get_overflowing_images(UpperCamelCase_ , encoded_inputs['overflow_to_sample_mapping'] ) UpperCAmelCase__ : int = images return encoded_inputs def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image UpperCAmelCase__ : List[Any] = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(UpperCamelCase_ ) != len(UpperCamelCase_ ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' F''' {len(UpperCamelCase_ )} and {len(UpperCamelCase_ )}''' ) return images_with_overflow def __snake_case ( self , *UpperCamelCase_ , **UpperCamelCase_ ): return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def __snake_case ( self , *UpperCamelCase_ , **UpperCamelCase_ ): return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ ) @property def __snake_case ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __snake_case ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , UpperCamelCase_ , ) return self.image_processor_class @property def __snake_case ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , UpperCamelCase_ , ) return self.image_processor
110
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
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 UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ) -> Optional[Any]: # A mock response for an HTTP head request to emulate server down snake_case_ = mock.Mock() snake_case_ = 5_00 snake_case_ = {} snake_case_ = HTTPError snake_case_ = {} # Download this model to make sure it's in the cache. snake_case_ = 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: snake_case_ = 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 ) -> List[Any]: # A mock response for an HTTP head request to emulate server down snake_case_ = mock.Mock() snake_case_ = 5_00 snake_case_ = {} snake_case_ = HTTPError snake_case_ = {} # Download this model to make sure it's in the cache. snake_case_ = 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: snake_case_ = GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _UpperCamelCase ( self ) -> Optional[int]: # This test is for deprecated behavior and can be removed in v5 try: snake_case_ = tempfile.mktemp() with open(a , 'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' , a ) snake_case_ = 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 ) snake_case_ = 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 , 10_00 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _UpperCamelCase ( self ) -> int: # This test is for deprecated behavior and can be removed in v5 snake_case_ = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' lowerCAmelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def _UpperCamelCase ( cls ) -> int: snake_case_ = TOKEN HfFolder.save_token(a ) @classmethod def _UpperCamelCase ( cls ) -> Dict: 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 ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = 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] ) ) snake_case_ = BertTokenizer(a ) tokenizer.push_to_hub('test-tokenizer' , use_auth_token=self._token ) snake_case_ = 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 ) snake_case_ = BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def _UpperCamelCase ( self ) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = 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] ) ) snake_case_ = BertTokenizer(a ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' , use_auth_token=self._token ) snake_case_ = 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 ) snake_case_ = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def _UpperCamelCase ( self ) -> int: CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = 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] ) ) snake_case_ = CustomTokenizer(a ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) snake_case_ = 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: snake_case_ = 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] ) ) snake_case_ = BertTokenizerFast.from_pretrained(a ) bert_tokenizer.save_pretrained(a ) snake_case_ = CustomTokenizerFast.from_pretrained(a ) tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) snake_case_ = 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' ) snake_case_ = 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 UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ) -> Any: snake_case_ = 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 ) -> List[str]: snake_case_ = 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 ) -> Tuple: snake_case_ = Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) , ['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) , ['BC', 'A'] ) def _UpperCamelCase ( self ) -> Optional[int]: snake_case_ = 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 ) -> Tuple: snake_case_ = 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 ) -> Union[str, Any]: snake_case_ = Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) , ['AB', 'C'] ) def _UpperCamelCase ( self ) -> List[Any]: snake_case_ = Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) , ['ABC', 'D'] ) def _UpperCamelCase ( self ) -> Union[str, Any]: # Even if the offsets are wrong, we necessarily output correct string # parts. snake_case_ = Trie() snake_case_ = trie.cut_text('ABC' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(a , ['AB', 'C'] )
198
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging lowercase_ = logging.get_logger(__name__) def a__ ( snake_case ): """simple docstring""" if isinstance(snake_case , np.ndarray ): return list(tensor.shape ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.shape(snake_case ) if tensor.shape == tf.TensorShape(snake_case ): return dynamic __SCREAMING_SNAKE_CASE : Any = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(snake_case )] def a__ ( snake_case , snake_case = None , snake_case = None ): """simple docstring""" return tf.nn.softmax(logits=logits + 1E-9 , axis=snake_case , name=snake_case ) def a__ ( snake_case , snake_case , snake_case , snake_case=1E-5 , snake_case=-1 ): """simple docstring""" # This is a very simplified functional layernorm, designed to duplicate # the functionality of PyTorch nn.functional.layer_norm when this is needed to port # models in Transformers. if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(snake_case , snake_case ): raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.''' ) # Get mean and variance on the axis to be normalized __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = tf.nn.moments(snake_case , axes=[axis] , keepdims=snake_case ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis __SCREAMING_SNAKE_CASE : int = [1] * inputs.shape.rank __SCREAMING_SNAKE_CASE : List[str] = shape_list(snake_case )[axis] __SCREAMING_SNAKE_CASE : str = tf.reshape(snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.reshape(snake_case , snake_case ) # Compute layer normalization using the batch_normalization # function. __SCREAMING_SNAKE_CASE : int = tf.nn.batch_normalization( snake_case , snake_case , snake_case , offset=snake_case , scale=snake_case , variance_epsilon=snake_case , ) return outputs def a__ ( snake_case , snake_case=0 , snake_case=-1 ): """simple docstring""" # Replicates the behavior of torch.flatten in TF # If end_dim or start_dim is negative, count them from the end if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input __SCREAMING_SNAKE_CASE : int = tf.shape(snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) __SCREAMING_SNAKE_CASE : int = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(snake_case , snake_case ) def a__ ( snake_case ): """simple docstring""" if not isinstance(snake_case , tf.Tensor ): __SCREAMING_SNAKE_CASE : Tuple = tf.convert_to_tensor(snake_case ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: __SCREAMING_SNAKE_CASE : str = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: __SCREAMING_SNAKE_CASE : Optional[Any] = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) __SCREAMING_SNAKE_CASE : int = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def a__ ( snake_case , snake_case , snake_case = "input_ids" ): """simple docstring""" tf.debugging.assert_less( snake_case , tf.cast(snake_case , dtype=tensor.dtype ) , message=( F'''The maximum value of {tensor_name} ({tf.math.reduce_max(snake_case )}) must be smaller than the embedding ''' F'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = 64_512 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. __SCREAMING_SNAKE_CASE : Dict = [x for x in data if len(snake_case ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( '''The following attributes cannot be saved to HDF5 file because ''' F'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' F'''bytes: {bad_attributes}''' ) __SCREAMING_SNAKE_CASE : str = np.asarray(snake_case ) __SCREAMING_SNAKE_CASE : int = 1 __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array_split(snake_case , snake_case ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 __SCREAMING_SNAKE_CASE : List[Any] = np.array_split(snake_case , snake_case ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(snake_case ): __SCREAMING_SNAKE_CASE : Any = chunk_data else: __SCREAMING_SNAKE_CASE : int = data def a__ ( snake_case , snake_case ): """simple docstring""" if name in group.attrs: __SCREAMING_SNAKE_CASE : List[str] = [n.decode('''utf8''' ) if hasattr(snake_case , '''decode''' ) else n for n in group.attrs[name]] else: __SCREAMING_SNAKE_CASE : Any = [] __SCREAMING_SNAKE_CASE : List[str] = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('''utf8''' ) if hasattr(snake_case , '''decode''' ) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]] ) chunk_id += 1 return data def a__ ( snake_case ): """simple docstring""" def _expand_single_ad_tensor(snake_case ): if isinstance(snake_case , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(snake_case , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , snake_case )
74
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MobileBertTokenizer lowerCAmelCase_ = MobileBertTokenizerFast lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = filter_non_english lowerCAmelCase_ = '''google/mobilebert-uncased''' def UpperCAmelCase__ ( self : Dict ): """simple docstring""" super().setUp() __SCREAMING_SNAKE_CASE : List[str] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : int = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def UpperCAmelCase__ ( self : Tuple , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : List[str] = '''unwanted, running''' return input_text, output_text def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase__ ( self : int ): """simple docstring""" if not self.test_rust_tokenizer: return __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : str = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Any = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : str = tokenizer.encode(_A ) __SCREAMING_SNAKE_CASE : Any = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) # With lower casing __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer(do_lower_case=_A ) __SCREAMING_SNAKE_CASE : List[str] = self.get_rust_tokenizer(do_lower_case=_A ) __SCREAMING_SNAKE_CASE : List[str] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : int = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BasicTokenizer(do_lower_case=_A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] __SCREAMING_SNAKE_CASE : Dict = {} for i, token in enumerate(_A ): __SCREAMING_SNAKE_CASE : List[str] = i __SCREAMING_SNAKE_CASE : str = WordpieceTokenizer(vocab=_A , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def UpperCAmelCase__ ( self : str ): """simple docstring""" self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(_A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(_A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode('''sequence builders''' , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Any = tokenizer.build_inputs_with_special_tokens(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : str = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_r.encode_plus( _A , return_attention_mask=_A , return_token_type_ids=_A , return_offsets_mapping=_A , add_special_tokens=_A , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_r.do_lower_case if hasattr(_A , '''do_lower_case''' ) else False __SCREAMING_SNAKE_CASE : Optional[Any] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = ['''的''', '''人''', '''有'''] __SCREAMING_SNAKE_CASE : int = ''''''.join(_A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : int = self.tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : int = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer_p.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer_r.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_r.convert_ids_to_tokens(_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = False __SCREAMING_SNAKE_CASE : Any = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Dict = tokenizer_r.convert_ids_to_tokens(_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE : List[Any] = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(_A ) ] self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A )
74
1
import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) lowercase_ = logging.getLogger() def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = {} __SCREAMING_SNAKE_CASE : List[str] = os.path.join(snake_case , '''all_results.json''' ) if os.path.exists(snake_case ): with open(snake_case , '''r''' ) as f: __SCREAMING_SNAKE_CASE : List[str] = json.load(snake_case ) else: raise ValueError(F'''can\'t find {path}''' ) return results lowercase_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" import xla_spawn __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_auto_remove_tmp_dir() __SCREAMING_SNAKE_CASE : Dict = F''' ./examples/pytorch/text-classification/run_glue.py --num_cores=8 ./examples/pytorch/text-classification/run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --overwrite_output_dir --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --do_train --do_eval --debug tpu_metrics_debug --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --max_steps=10 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(_A , '''argv''' , _A ): __SCREAMING_SNAKE_CASE : str = time() xla_spawn.main() __SCREAMING_SNAKE_CASE : Any = time() __SCREAMING_SNAKE_CASE : Dict = get_results(_A ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 500 ) def UpperCAmelCase__ ( self : int ): """simple docstring""" import xla_spawn __SCREAMING_SNAKE_CASE : Optional[Any] = ''' ./tests/test_trainer_tpu.py --num_cores=8 ./tests/test_trainer_tpu.py '''.split() with patch.object(_A , '''argv''' , _A ): xla_spawn.main()
74
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor lowercase_ = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : Tuple , *_A : Optional[int] , **_A : Tuple ): """simple docstring""" warnings.warn( '''The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use MobileViTImageProcessor instead.''' , _A , ) super().__init__(*_A , **_A )
74
1
import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Union[str, Any] , _A : Dict , _A : List[Any]=2 , _A : int=56 , _A : Tuple=True , _A : Any=True , _A : List[Any]=True , _A : List[Any]=True , _A : Optional[Any]=99 , _A : Optional[int]=32 , _A : Optional[int]=2 , _A : Optional[int]=2 , _A : int=7 , _A : Dict="gelu_new" , _A : Union[str, Any]=0.1 , _A : str=0.1 , _A : Optional[int]=512 , _A : Optional[int]=16 , _A : Any=2 , _A : List[str]=0.02 , _A : List[Any]=4 , _A : Dict="block_sparse" , _A : Dict=True , _A : str=False , _A : str=2 , _A : Union[str, Any]=3 , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = parent __SCREAMING_SNAKE_CASE : List[Any] = batch_size __SCREAMING_SNAKE_CASE : List[str] = seq_length __SCREAMING_SNAKE_CASE : str = is_training __SCREAMING_SNAKE_CASE : Union[str, Any] = use_attention_mask __SCREAMING_SNAKE_CASE : Any = use_token_type_ids __SCREAMING_SNAKE_CASE : Tuple = use_labels __SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size __SCREAMING_SNAKE_CASE : str = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : str = num_attention_heads __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Any = hidden_act __SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob __SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : str = max_position_embeddings __SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size __SCREAMING_SNAKE_CASE : Any = type_sequence_label_size __SCREAMING_SNAKE_CASE : List[Any] = initializer_range __SCREAMING_SNAKE_CASE : Tuple = num_choices __SCREAMING_SNAKE_CASE : Optional[Any] = rescale_embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = attention_type __SCREAMING_SNAKE_CASE : Optional[int] = use_bias __SCREAMING_SNAKE_CASE : Any = block_size __SCREAMING_SNAKE_CASE : Any = num_random_blocks def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : List[Any] = None if self.use_attention_mask: __SCREAMING_SNAKE_CASE : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE : Optional[int] = BigBirdConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : str = config_and_inputs __SCREAMING_SNAKE_CASE : int = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask, } return config, inputs_dict @require_flax class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) lowerCAmelCase_ = False lowerCAmelCase_ = False def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCAmelCase__ ( self : int ): """simple docstring""" super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" super().test_hidden_states_output() @slow def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" for model_class_name in self.all_model_classes: __SCREAMING_SNAKE_CASE : List[str] = model_class_name.from_pretrained('''google/bigbird-roberta-base''' ) self.assertIsNotNone(_A ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._prepare_for_class(_A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = model_class(_A ) @jax.jit def model_jitted(_A : Tuple , _A : Optional[Any]=None , **_A : Optional[Any] ): return model(input_ids=_A , attention_mask=_A , **_A ) with self.subTest('''JIT Enabled''' ): __SCREAMING_SNAKE_CASE : Union[str, Any] = model_jitted(**_A ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model_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 : List[Any] , _A : Any , _A : List[str] , _A : int , _A : List[str]=1e-5 , _A : Union[str, Any]="outputs" , _A : Optional[int]=None ): """simple docstring""" if name.startswith('''outputs.attentions''' ): return else: super().check_pt_flax_outputs(_A , _A , _A , _A , _A , _A )
74
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast lowercase_ = datasets.utils.logging.get_logger(__name__) @dataclass class __UpperCamelCase ( datasets.BuilderConfig ): """simple docstring""" lowerCAmelCase_ = 1_00_00 lowerCAmelCase_ = None lowerCAmelCase_ = None class __UpperCamelCase ( datasets.ArrowBasedBuilder ): """simple docstring""" lowerCAmelCase_ = ParquetConfig def UpperCAmelCase__ ( self : Any ): """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def UpperCAmelCase__ ( self : Any , _A : Optional[Any] ): """simple docstring""" 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}''' ) __SCREAMING_SNAKE_CASE : List[str] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_A , (str, list, tuple) ): __SCREAMING_SNAKE_CASE : Tuple = data_files if isinstance(_A , _A ): __SCREAMING_SNAKE_CASE : Optional[int] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __SCREAMING_SNAKE_CASE : List[Any] = [dl_manager.iter_files(_A ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] __SCREAMING_SNAKE_CASE : int = [] for split_name, files in data_files.items(): if isinstance(_A , _A ): __SCREAMING_SNAKE_CASE : Any = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __SCREAMING_SNAKE_CASE : Optional[int] = [dl_manager.iter_files(_A ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(_A ): with open(_A , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : Dict = datasets.Features.from_arrow_schema(pq.read_schema(_A ) ) break splits.append(datasets.SplitGenerator(name=_A , gen_kwargs={'''files''': files} ) ) return splits def UpperCAmelCase__ ( self : str , _A : pa.Table ): """simple docstring""" if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example __SCREAMING_SNAKE_CASE : str = table_cast(_A , self.info.features.arrow_schema ) return pa_table def UpperCAmelCase__ ( self : Tuple , _A : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F'''Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'''' ) for file_idx, file in enumerate(itertools.chain.from_iterable(_A ) ): with open(_A , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : str = pq.ParquetFile(_A ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): __SCREAMING_SNAKE_CASE : Optional[Any] = pa.Table.from_batches([record_batch] ) # 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 F'''{file_idx}_{batch_idx}''', self._cast_table(_A ) except ValueError as e: logger.error(F'''Failed to read file \'{file}\' with error {type(_A )}: {e}''' ) raise
74
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = 42 lowerCAmelCase_ = jnp.floataa lowerCAmelCase_ = True def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" super().setup() __SCREAMING_SNAKE_CASE : Optional[int] = nn.Dense(5 , dtype=self.dtype ) def __call__( self : Tuple , *_A : List[Any] , **_A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = super().__call__(*_A , **_A ) __SCREAMING_SNAKE_CASE : List[str] = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = FlaxBigBirdForNaturalQuestionsModule def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case , snake_case ): """simple docstring""" def cross_entropy(snake_case , snake_case , snake_case=None ): __SCREAMING_SNAKE_CASE : Optional[int] = logits.shape[-1] __SCREAMING_SNAKE_CASE : Any = (labels[..., None] == jnp.arange(snake_case )[None]).astype('''f4''' ) __SCREAMING_SNAKE_CASE : str = jax.nn.log_softmax(snake_case , axis=-1 ) __SCREAMING_SNAKE_CASE : Optional[Any] = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: __SCREAMING_SNAKE_CASE : List[Any] = reduction(snake_case ) return loss __SCREAMING_SNAKE_CASE : List[str] = partial(snake_case , reduction=jnp.mean ) __SCREAMING_SNAKE_CASE : int = cross_entropy(snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Any = cross_entropy(snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Dict = cross_entropy(snake_case , snake_case ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = "google/bigbird-roberta-base" lowerCAmelCase_ = 30_00 lowerCAmelCase_ = 1_05_00 lowerCAmelCase_ = 1_28 lowerCAmelCase_ = 3 lowerCAmelCase_ = 1 lowerCAmelCase_ = 5 # tx_args lowerCAmelCase_ = 3E-5 lowerCAmelCase_ = 0.0 lowerCAmelCase_ = 2_00_00 lowerCAmelCase_ = 0.0095 lowerCAmelCase_ = "bigbird-roberta-natural-questions" lowerCAmelCase_ = "training-expt" lowerCAmelCase_ = "data/nq-training.jsonl" lowerCAmelCase_ = "data/nq-validation.jsonl" def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" os.makedirs(self.base_dir , exist_ok=_A ) __SCREAMING_SNAKE_CASE : Tuple = os.path.join(self.base_dir , self.save_dir ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.batch_size_per_device * jax.device_count() @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = 42 lowerCAmelCase_ = 40_96 # no dynamic padding on TPUs def __call__( self : List[str] , _A : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.collate_fn(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = jax.tree_util.tree_map(_A , _A ) return batch def UpperCAmelCase__ ( self : List[Any] , _A : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = self.fetch_inputs(features['''input_ids'''] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''input_ids''': jnp.array(_A , dtype=jnp.intaa ), '''attention_mask''': jnp.array(_A , dtype=jnp.intaa ), '''start_labels''': jnp.array(features['''start_token'''] , dtype=jnp.intaa ), '''end_labels''': jnp.array(features['''end_token'''] , dtype=jnp.intaa ), '''pooled_labels''': jnp.array(features['''category'''] , dtype=jnp.intaa ), } return batch def UpperCAmelCase__ ( self : Any , _A : list ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = [self._fetch_inputs(_A ) for ids in input_ids] return zip(*_A ) def UpperCAmelCase__ ( self : List[str] , _A : list ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = [1 for _ in range(len(_A ) )] while len(_A ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def a__ ( snake_case , snake_case , snake_case=None ): """simple docstring""" if seed is not None: __SCREAMING_SNAKE_CASE : Any = dataset.shuffle(seed=snake_case ) for i in range(len(snake_case ) // batch_size ): __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset[i * batch_size : (i + 1) * batch_size] yield dict(snake_case ) @partial(jax.pmap , axis_name='''batch''' ) def a__ ( snake_case , snake_case , **snake_case ): """simple docstring""" def loss_fn(snake_case ): __SCREAMING_SNAKE_CASE : Tuple = model_inputs.pop('''start_labels''' ) __SCREAMING_SNAKE_CASE : str = model_inputs.pop('''end_labels''' ) __SCREAMING_SNAKE_CASE : List[str] = model_inputs.pop('''pooled_labels''' ) __SCREAMING_SNAKE_CASE : Tuple = state.apply_fn(**snake_case , params=snake_case , dropout_rng=snake_case , train=snake_case ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs return state.loss_fn( snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = jax.random.split(snake_case ) __SCREAMING_SNAKE_CASE : int = jax.value_and_grad(snake_case ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = grad_fn(state.params ) __SCREAMING_SNAKE_CASE : Tuple = jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = jax.lax.pmean(snake_case , '''batch''' ) __SCREAMING_SNAKE_CASE : Any = state.apply_gradients(grads=snake_case ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name='''batch''' ) def a__ ( snake_case , **snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = model_inputs.pop('''start_labels''' ) __SCREAMING_SNAKE_CASE : Dict = model_inputs.pop('''end_labels''' ) __SCREAMING_SNAKE_CASE : Any = model_inputs.pop('''pooled_labels''' ) __SCREAMING_SNAKE_CASE : Dict = state.apply_fn(**snake_case , params=state.params , train=snake_case ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = outputs __SCREAMING_SNAKE_CASE : int = state.loss_fn(snake_case , snake_case , snake_case , snake_case , snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Dict = jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) return metrics class __UpperCamelCase ( train_state.TrainState ): """simple docstring""" lowerCAmelCase_ = struct.field(pytree_node=lowerCAmelCase__ ) @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None def UpperCAmelCase__ ( self : int , _A : Optional[Any] , _A : str , _A : Optional[int] , _A : List[str]=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = model.params __SCREAMING_SNAKE_CASE : int = TrainState.create( apply_fn=model.__call__ , params=_A , tx=_A , loss_fn=_A , ) if ckpt_dir is not None: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = restore_checkpoint(_A , _A ) __SCREAMING_SNAKE_CASE : Dict = { '''lr''': args.lr, '''init_lr''': args.init_lr, '''warmup_steps''': args.warmup_steps, '''num_train_steps''': num_train_steps, '''weight_decay''': args.weight_decay, } __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = build_tx(**_A ) __SCREAMING_SNAKE_CASE : Tuple = train_state.TrainState( step=_A , apply_fn=model.__call__ , params=_A , tx=_A , opt_state=_A , ) __SCREAMING_SNAKE_CASE : str = args __SCREAMING_SNAKE_CASE : Optional[Any] = data_collator __SCREAMING_SNAKE_CASE : Dict = lr __SCREAMING_SNAKE_CASE : Union[str, Any] = params __SCREAMING_SNAKE_CASE : Dict = jax_utils.replicate(_A ) return state def UpperCAmelCase__ ( self : Optional[int] , _A : List[str] , _A : int , _A : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.args __SCREAMING_SNAKE_CASE : Tuple = len(_A ) // args.batch_size __SCREAMING_SNAKE_CASE : List[str] = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE : Any = jax.random.split(_A , jax.device_count() ) for epoch in range(args.max_epochs ): __SCREAMING_SNAKE_CASE : List[Any] = jnp.array(0 , dtype=jnp.floataa ) __SCREAMING_SNAKE_CASE : Optional[int] = get_batched_dataset(_A , args.batch_size , seed=_A ) __SCREAMING_SNAKE_CASE : Dict = 0 for batch in tqdm(_A , total=_A , desc=F'''Running EPOCH-{epoch}''' ): __SCREAMING_SNAKE_CASE : List[Any] = self.data_collator(_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = self.train_step_fn(_A , _A , **_A ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 if i % args.logging_steps == 0: __SCREAMING_SNAKE_CASE : Dict = jax_utils.unreplicate(state.step ) __SCREAMING_SNAKE_CASE : int = running_loss.item() / i __SCREAMING_SNAKE_CASE : Dict = self.scheduler_fn(state_step - 1 ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.evaluate(_A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''step''': state_step.item(), '''eval_loss''': eval_loss.item(), '''tr_loss''': tr_loss, '''lr''': lr.item(), } tqdm.write(str(_A ) ) self.logger.log(_A , commit=_A ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F'''-e{epoch}-s{i}''' , state=_A ) def UpperCAmelCase__ ( self : int , _A : Any , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = get_batched_dataset(_A , self.args.batch_size ) __SCREAMING_SNAKE_CASE : Optional[Any] = len(_A ) // self.args.batch_size __SCREAMING_SNAKE_CASE : Any = jnp.array(0 , dtype=jnp.floataa ) __SCREAMING_SNAKE_CASE : Optional[Any] = 0 for batch in tqdm(_A , total=_A , desc='''Evaluating ... ''' ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.data_collator(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = self.val_step_fn(_A , **_A ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 return running_loss / i def UpperCAmelCase__ ( self : Optional[Any] , _A : Optional[Any] , _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = jax_utils.unreplicate(_A ) print(F'''SAVING CHECKPOINT IN {save_dir}''' , end=''' ... ''' ) self.model_save_fn(_A , params=state.params ) with open(os.path.join(_A , '''opt_state.msgpack''' ) , '''wb''' ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(_A , '''args.joblib''' ) ) joblib.dump(self.data_collator , os.path.join(_A , '''data_collator.joblib''' ) ) with open(os.path.join(_A , '''training_state.json''' ) , '''w''' ) as f: json.dump({'''step''': state.step.item()} , _A ) print('''DONE''' ) def a__ ( snake_case , snake_case ): """simple docstring""" print(F'''RESTORING CHECKPOINT FROM {save_dir}''' , end=''' ... ''' ) with open(os.path.join(snake_case , '''flax_model.msgpack''' ) , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : str = from_bytes(state.params , f.read() ) with open(os.path.join(snake_case , '''opt_state.msgpack''' ) , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : List[str] = from_bytes(state.opt_state , f.read() ) __SCREAMING_SNAKE_CASE : Optional[int] = joblib.load(os.path.join(snake_case , '''args.joblib''' ) ) __SCREAMING_SNAKE_CASE : List[str] = joblib.load(os.path.join(snake_case , '''data_collator.joblib''' ) ) with open(os.path.join(snake_case , '''training_state.json''' ) , '''r''' ) as f: __SCREAMING_SNAKE_CASE : str = json.load(snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = training_state['''step'''] print('''DONE''' ) return params, opt_state, step, args, data_collator def a__ ( snake_case , snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = num_train_steps - warmup_steps __SCREAMING_SNAKE_CASE : List[Any] = optax.linear_schedule(init_value=snake_case , end_value=snake_case , transition_steps=snake_case ) __SCREAMING_SNAKE_CASE : Optional[int] = optax.linear_schedule(init_value=snake_case , end_value=1E-7 , transition_steps=snake_case ) __SCREAMING_SNAKE_CASE : List[str] = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case ): """simple docstring""" def weight_decay_mask(snake_case ): __SCREAMING_SNAKE_CASE : int = traverse_util.flatten_dict(snake_case ) __SCREAMING_SNAKE_CASE : Optional[Any] = {k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()} return traverse_util.unflatten_dict(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = scheduler_fn(snake_case , snake_case , snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Any = optax.adamw(learning_rate=snake_case , weight_decay=snake_case , mask=snake_case ) return tx, lr
74
from math import isclose, sqrt def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = point_y / 4 / point_x __SCREAMING_SNAKE_CASE : int = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __SCREAMING_SNAKE_CASE : Tuple = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __SCREAMING_SNAKE_CASE : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __SCREAMING_SNAKE_CASE : int = outgoing_gradient**2 + 4 __SCREAMING_SNAKE_CASE : List[str] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __SCREAMING_SNAKE_CASE : Optional[Any] = (point_y - outgoing_gradient * point_x) ** 2 - 100 __SCREAMING_SNAKE_CASE : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __SCREAMING_SNAKE_CASE : int = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __SCREAMING_SNAKE_CASE : Dict = x_minus if isclose(snake_case , snake_case ) else x_plus __SCREAMING_SNAKE_CASE : Dict = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def a__ ( snake_case = 1.4 , snake_case = -9.6 ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : float = first_x_coord __SCREAMING_SNAKE_CASE : float = first_y_coord __SCREAMING_SNAKE_CASE : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = next_point(snake_case , snake_case , snake_case ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
74
1
def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = [0 for i in range(len(snake_case ) )] # initialize interval's left pointer and right pointer __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = 0, 0 for i in range(1 , len(snake_case ) ): # case when current index is inside the interval if i <= right_pointer: __SCREAMING_SNAKE_CASE : List[Any] = min(right_pointer - i + 1 , z_result[i - left_pointer] ) __SCREAMING_SNAKE_CASE : Dict = min_edge while go_next(snake_case , snake_case , snake_case ): 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: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = i, i + z_result[i] - 1 return z_result def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" return i + z_result[i] < len(snake_case ) and s[z_result[i]] == s[i + z_result[i]] def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string __SCREAMING_SNAKE_CASE : str = 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(snake_case ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
74
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , _A : int , _A : Any=7 , _A : List[str]=3 , _A : Optional[Any]=18 , _A : List[str]=30 , _A : Optional[Any]=400 , _A : Any=True , _A : List[str]=None , _A : Union[str, Any]=True , _A : Optional[int]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else {'''shortest_edge''': 20} __SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} __SCREAMING_SNAKE_CASE : int = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : List[str] = image_size __SCREAMING_SNAKE_CASE : int = min_resolution __SCREAMING_SNAKE_CASE : Optional[int] = max_resolution __SCREAMING_SNAKE_CASE : List[Any] = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : str = do_center_crop __SCREAMING_SNAKE_CASE : Any = crop_size def UpperCAmelCase__ ( self : Dict ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MobileNetVaImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = MobileNetVaImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , '''do_resize''' ) ) self.assertTrue(hasattr(_A , '''size''' ) ) self.assertTrue(hasattr(_A , '''do_center_crop''' ) ) self.assertTrue(hasattr(_A , '''crop_size''' ) ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) __SCREAMING_SNAKE_CASE : Tuple = 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 : int ): """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Any = 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 __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Any = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Optional[Any] = 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 __SCREAMING_SNAKE_CASE : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Dict = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
74
1
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig lowercase_ = { """susnato/ernie-m-base_pytorch""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json""", """susnato/ernie-m-large_pytorch""": """https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json""", } class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = '''ernie_m''' lowerCAmelCase_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self : List[str] , _A : int = 25_0002 , _A : int = 768 , _A : int = 12 , _A : int = 12 , _A : int = 3072 , _A : str = "gelu" , _A : float = 0.1 , _A : float = 0.1 , _A : int = 514 , _A : float = 0.02 , _A : int = 1 , _A : float = 1e-05 , _A : Optional[Any]=None , _A : Optional[Any]=False , _A : int=0.0 , **_A : List[str] , ): """simple docstring""" super().__init__(pad_token_id=_A , **_A ) __SCREAMING_SNAKE_CASE : Any = vocab_size __SCREAMING_SNAKE_CASE : List[Any] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Tuple = num_attention_heads __SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size __SCREAMING_SNAKE_CASE : List[Any] = hidden_act __SCREAMING_SNAKE_CASE : int = hidden_dropout_prob __SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Optional[int] = max_position_embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range __SCREAMING_SNAKE_CASE : Tuple = layer_norm_eps __SCREAMING_SNAKE_CASE : List[Any] = classifier_dropout __SCREAMING_SNAKE_CASE : str = is_decoder __SCREAMING_SNAKE_CASE : Tuple = act_dropout
74
def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = [0 for i in range(len(snake_case ) )] # initialize interval's left pointer and right pointer __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = 0, 0 for i in range(1 , len(snake_case ) ): # case when current index is inside the interval if i <= right_pointer: __SCREAMING_SNAKE_CASE : List[Any] = min(right_pointer - i + 1 , z_result[i - left_pointer] ) __SCREAMING_SNAKE_CASE : Dict = min_edge while go_next(snake_case , snake_case , snake_case ): 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: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = i, i + z_result[i] - 1 return z_result def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" return i + z_result[i] < len(snake_case ) and s[z_result[i]] == s[i + z_result[i]] def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string __SCREAMING_SNAKE_CASE : str = 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(snake_case ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
74
1
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''input_values''', '''attention_mask'''] def __init__( self : Tuple , _A : int = 1 , _A : int = 1_6000 , _A : float = 0.0 , _A : bool = False , _A : int = 80 , _A : int = 16 , _A : int = 64 , _A : str = "hann_window" , _A : float = 1.0 , _A : float = 80 , _A : float = 7600 , _A : float = 1e-10 , _A : int = 2 , _A : bool = True , **_A : Optional[Any] , ): """simple docstring""" super().__init__(feature_size=_A , sampling_rate=_A , padding_value=_A , **_A ) __SCREAMING_SNAKE_CASE : List[Any] = do_normalize __SCREAMING_SNAKE_CASE : Optional[Any] = return_attention_mask __SCREAMING_SNAKE_CASE : Optional[Any] = num_mel_bins __SCREAMING_SNAKE_CASE : Dict = hop_length __SCREAMING_SNAKE_CASE : Any = win_length __SCREAMING_SNAKE_CASE : Union[str, Any] = win_function __SCREAMING_SNAKE_CASE : str = frame_signal_scale __SCREAMING_SNAKE_CASE : Tuple = fmin __SCREAMING_SNAKE_CASE : Any = fmax __SCREAMING_SNAKE_CASE : Dict = mel_floor __SCREAMING_SNAKE_CASE : Union[str, Any] = reduction_factor __SCREAMING_SNAKE_CASE : List[str] = win_length * sampling_rate // 1000 __SCREAMING_SNAKE_CASE : List[Any] = hop_length * sampling_rate // 1000 __SCREAMING_SNAKE_CASE : Union[str, Any] = optimal_fft_length(self.sample_size ) __SCREAMING_SNAKE_CASE : str = (self.n_fft // 2) + 1 __SCREAMING_SNAKE_CASE : Optional[int] = window_function(window_length=self.sample_size , name=self.win_function , periodic=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm='''slaney''' , mel_scale='''slaney''' , ) if frame_signal_scale != 1.0: warnings.warn( '''The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers''' , _A , ) if reduction_factor != 2.0: warnings.warn( '''The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers''' , _A , ) @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def UpperCAmelCase__ ( _A : List[np.ndarray] , _A : List[np.ndarray] , _A : float = 0.0 ): """simple docstring""" if attention_mask is not None: __SCREAMING_SNAKE_CASE : Optional[int] = np.array(_A , np.intaa ) __SCREAMING_SNAKE_CASE : List[Any] = [] for vector, length in zip(_A , attention_mask.sum(-1 ) ): __SCREAMING_SNAKE_CASE : Tuple = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: __SCREAMING_SNAKE_CASE : Any = padding_value normed_input_values.append(_A ) else: __SCREAMING_SNAKE_CASE : int = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def UpperCAmelCase__ ( self : Any , _A : np.ndarray , ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = spectrogram( _A , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel='''log10''' , ) return log_mel_spec.T def __call__( self : Dict , _A : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , _A : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , _A : Union[bool, str, PaddingStrategy] = False , _A : Optional[int] = None , _A : bool = False , _A : Optional[int] = None , _A : Optional[bool] = None , _A : Optional[Union[str, TensorType]] = None , _A : Optional[int] = None , **_A : str , ): """simple docstring""" if audio is None and audio_target is None: raise ValueError('''You must provide either `audio` or `audio_target` values.''' ) if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with''' F''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) if audio is not None: __SCREAMING_SNAKE_CASE : str = self._process_audio( _A , _A , _A , _A , _A , _A , _A , _A , **_A , ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = None if audio_target is not None: __SCREAMING_SNAKE_CASE : List[Any] = self._process_audio( _A , _A , _A , _A , _A , _A , _A , _A , **_A , ) if inputs is None: return inputs_target else: __SCREAMING_SNAKE_CASE : str = inputs_target['''input_values'''] __SCREAMING_SNAKE_CASE : Dict = inputs_target.get('''attention_mask''' ) if decoder_attention_mask is not None: __SCREAMING_SNAKE_CASE : Tuple = decoder_attention_mask return inputs def UpperCAmelCase__ ( self : Tuple , _A : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , _A : bool = False , _A : Union[bool, str, PaddingStrategy] = False , _A : Optional[int] = None , _A : bool = False , _A : Optional[int] = None , _A : Optional[bool] = None , _A : Optional[Union[str, TensorType]] = None , **_A : str , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = isinstance(_A , np.ndarray ) and len(speech.shape ) > 1 if is_batched_numpy and len(speech.shape ) > 2: raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' ) __SCREAMING_SNAKE_CASE : int = is_batched_numpy or ( isinstance(_A , (list, tuple) ) and (isinstance(speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __SCREAMING_SNAKE_CASE : Tuple = [np.asarray(_A , dtype=np.floataa ) for speech in speech] elif not is_batched and not isinstance(_A , np.ndarray ): __SCREAMING_SNAKE_CASE : Any = np.asarray(_A , dtype=np.floataa ) elif isinstance(_A , np.ndarray ) and speech.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE : Tuple = speech.astype(np.floataa ) # always return batch if not is_batched: __SCREAMING_SNAKE_CASE : Optional[int] = [speech] # needed to make pad() work on spectrogram inputs __SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_size # convert into correct format for padding if is_target: __SCREAMING_SNAKE_CASE : Tuple = [self._extract_mel_features(_A ) for waveform in speech] __SCREAMING_SNAKE_CASE : Tuple = BatchFeature({'''input_values''': features} ) __SCREAMING_SNAKE_CASE : Any = self.num_mel_bins else: __SCREAMING_SNAKE_CASE : Dict = BatchFeature({'''input_values''': speech} ) __SCREAMING_SNAKE_CASE : Dict = self.pad( _A , padding=_A , max_length=_A , truncation=_A , pad_to_multiple_of=_A , return_attention_mask=_A , **_A , ) __SCREAMING_SNAKE_CASE : List[Any] = feature_size_hack # convert input values to correct format __SCREAMING_SNAKE_CASE : str = padded_inputs['''input_values'''] if not isinstance(input_values[0] , np.ndarray ): __SCREAMING_SNAKE_CASE : Any = [np.asarray(_A , dtype=np.floataa ) for array in input_values] elif ( not isinstance(_A , np.ndarray ) and isinstance(input_values[0] , np.ndarray ) and input_values[0].dtype is np.dtype(np.floataa ) ): __SCREAMING_SNAKE_CASE : List[Any] = [array.astype(np.floataa ) for array in input_values] elif isinstance(_A , np.ndarray ) and input_values.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE : Any = input_values.astype(np.floataa ) # convert attention_mask to correct format __SCREAMING_SNAKE_CASE : List[str] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray(_A , dtype=np.intaa ) for array in attention_mask] # zero-mean and unit-variance normalization if not is_target and self.do_normalize: __SCREAMING_SNAKE_CASE : Optional[Any] = ( attention_mask if self._get_padding_strategies(_A , max_length=_A ) is not PaddingStrategy.DO_NOT_PAD else None ) __SCREAMING_SNAKE_CASE : List[str] = self.zero_mean_unit_var_norm( padded_inputs['''input_values'''] , attention_mask=_A , padding_value=self.padding_value ) if return_tensors is not None: __SCREAMING_SNAKE_CASE : str = padded_inputs.convert_to_tensors(_A ) return padded_inputs def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = super().to_dict() # Don't serialize these as they are derived from the other properties. __SCREAMING_SNAKE_CASE : int = ['''window''', '''mel_filters''', '''sample_size''', '''sample_stride''', '''n_fft''', '''n_freqs'''] for name in names: if name in output: del output[name] return output
74
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase_ = {"""configuration_swin""": ["""SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SwinConfig""", """SwinOnnxConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""", """SwinForImageClassification""", """SwinForMaskedImageModeling""", """SwinModel""", """SwinPreTrainedModel""", """SwinBackbone""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSwinForImageClassification""", """TFSwinForMaskedImageModeling""", """TFSwinModel""", """TFSwinPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
74
1
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class __UpperCamelCase : """simple docstring""" def __init__( self : Optional[Any] , _A : Optional[Any] , _A : str=13 , _A : Optional[int]=7 , _A : Any=True , _A : Tuple=True , _A : Any=False , _A : Optional[Any]=True , _A : Optional[int]=99 , _A : Dict=32 , _A : Any=5 , _A : int=4 , _A : Tuple=37 , _A : Optional[Any]="gelu" , _A : Tuple=0.1 , _A : str=0.1 , _A : str=512 , _A : Tuple=16 , _A : Any=2 , _A : Dict=0.02 , _A : Union[str, Any]=3 , _A : Optional[Any]=4 , _A : str=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : str = batch_size __SCREAMING_SNAKE_CASE : str = seq_length __SCREAMING_SNAKE_CASE : str = is_training __SCREAMING_SNAKE_CASE : Tuple = use_input_mask __SCREAMING_SNAKE_CASE : List[str] = use_token_type_ids __SCREAMING_SNAKE_CASE : List[Any] = use_labels __SCREAMING_SNAKE_CASE : List[Any] = vocab_size __SCREAMING_SNAKE_CASE : Any = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads __SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size __SCREAMING_SNAKE_CASE : str = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : str = max_position_embeddings __SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size __SCREAMING_SNAKE_CASE : int = type_sequence_label_size __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : List[str] = num_labels __SCREAMING_SNAKE_CASE : Tuple = num_choices __SCREAMING_SNAKE_CASE : str = scope def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : List[Any] = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : str = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE : str = None __SCREAMING_SNAKE_CASE : Dict = None __SCREAMING_SNAKE_CASE : List[str] = None if self.use_labels: __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : str ): """simple docstring""" return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , use_stable_embedding=_A , ) def UpperCAmelCase__ ( self : str , _A : str , _A : Optional[int] , _A : Dict , _A : Optional[int] , _A : Dict , _A : List[Any] , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = OpenLlamaModel(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = model(_A , attention_mask=_A ) __SCREAMING_SNAKE_CASE : List[Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : List[str] , _A : Optional[Any] , _A : Any , _A : Dict , _A : Union[str, Any] , _A : Dict , _A : str , _A : List[str] , _A : Optional[Any] , _A : int , ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : Optional[Any] = OpenLlamaModel(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __SCREAMING_SNAKE_CASE : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __SCREAMING_SNAKE_CASE : Tuple = 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 : Union[str, Any] , _A : Dict , _A : Any , _A : Optional[int] , _A : Optional[Any] , _A : str , _A : List[str] , _A : int , _A : Union[str, Any] , _A : Tuple , ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = OpenLlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = 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 : List[str] , _A : List[Any] , _A : Tuple , _A : Tuple , _A : Optional[Any] , _A : List[str] , _A : Dict , _A : List[str] , _A : Tuple , _A : Any , ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Optional[int] = OpenLlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __SCREAMING_SNAKE_CASE : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __SCREAMING_SNAKE_CASE : int = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE : int = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE : Any = torch.cat([input_mask, next_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE : List[str] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['''hidden_states'''][0] __SCREAMING_SNAKE_CASE : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['''hidden_states'''][0] # select random slice __SCREAMING_SNAKE_CASE : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE : Any = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE : Dict = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ) : int = config_and_inputs __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) lowerCAmelCase_ = (OpenLlamaForCausalLM,) if is_torch_available() else () lowerCAmelCase_ = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = False lowerCAmelCase_ = False def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = OpenLlamaModelTester(self ) __SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE : Optional[int] = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : List[Any] = 3 __SCREAMING_SNAKE_CASE : Optional[Any] = input_dict['''input_ids'''] __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(1 ).to(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : int = OpenLlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Any = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : List[Any] = 3 __SCREAMING_SNAKE_CASE : int = '''single_label_classification''' __SCREAMING_SNAKE_CASE : List[Any] = input_dict['''input_ids'''] __SCREAMING_SNAKE_CASE : Tuple = input_ids.ne(1 ).to(_A ) __SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : int = OpenLlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : List[str] = 3 __SCREAMING_SNAKE_CASE : Dict = '''multi_label_classification''' __SCREAMING_SNAKE_CASE : Union[str, Any] = input_dict['''input_ids'''] __SCREAMING_SNAKE_CASE : Any = input_ids.ne(1 ).to(_A ) __SCREAMING_SNAKE_CASE : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE : Optional[Any] = OpenLlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test''' ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def UpperCAmelCase__ ( self : int , _A : int ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : str = ids_tensor([1, 10] , config.vocab_size ) __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __SCREAMING_SNAKE_CASE : Any = OpenLlamaModel(_A ) original_model.to(_A ) original_model.eval() __SCREAMING_SNAKE_CASE : int = original_model(_A ).last_hidden_state __SCREAMING_SNAKE_CASE : Dict = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __SCREAMING_SNAKE_CASE : List[Any] = {'''type''': scaling_type, '''factor''': 10.0} __SCREAMING_SNAKE_CASE : Any = OpenLlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __SCREAMING_SNAKE_CASE : Any = scaled_model(_A ).last_hidden_state __SCREAMING_SNAKE_CASE : Optional[Any] = scaled_model(_A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_A , _A , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) )
74
import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = XCLIPTextConfig() # derive patch size from model name __SCREAMING_SNAKE_CASE : Tuple = model_name.find('''patch''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(model_name[start_idx + len('''patch''' ) : start_idx + len('''patch''' ) + 2] ) __SCREAMING_SNAKE_CASE : Tuple = XCLIPVisionConfig(patch_size=snake_case , num_frames=snake_case ) if "large" in model_name: __SCREAMING_SNAKE_CASE : Optional[Any] = 768 __SCREAMING_SNAKE_CASE : Optional[int] = 3_072 __SCREAMING_SNAKE_CASE : Optional[Any] = 12 __SCREAMING_SNAKE_CASE : Optional[Any] = 1_024 __SCREAMING_SNAKE_CASE : int = 4_096 __SCREAMING_SNAKE_CASE : Tuple = 16 __SCREAMING_SNAKE_CASE : Optional[int] = 24 __SCREAMING_SNAKE_CASE : Optional[int] = 768 __SCREAMING_SNAKE_CASE : Optional[int] = 3_072 if model_name == "xclip-large-patch14-16-frames": __SCREAMING_SNAKE_CASE : Any = 336 __SCREAMING_SNAKE_CASE : Any = XCLIPConfig.from_text_vision_configs(snake_case , snake_case ) if "large" in model_name: __SCREAMING_SNAKE_CASE : Any = 768 return config def a__ ( snake_case ): """simple docstring""" # text encoder if name == "token_embedding.weight": __SCREAMING_SNAKE_CASE : List[str] = name.replace('''token_embedding.weight''' , '''text_model.embeddings.token_embedding.weight''' ) if name == "positional_embedding": __SCREAMING_SNAKE_CASE : List[str] = name.replace('''positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "ln_1" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: __SCREAMING_SNAKE_CASE : str = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''c_proj''' , '''fc2''' ) if name.startswith('''transformer.resblocks''' ): __SCREAMING_SNAKE_CASE : Any = name.replace('''transformer.resblocks''' , '''text_model.encoder.layers''' ) if "attn.out_proj" in name and "message" not in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''attn.out_proj''' , '''self_attn.out_proj''' ) if "ln_final" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace('''ln_final''' , '''text_model.final_layer_norm''' ) # visual encoder if name == "visual.class_embedding": __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace('''visual.class_embedding''' , '''vision_model.embeddings.class_embedding''' ) if name == "visual.positional_embedding": __SCREAMING_SNAKE_CASE : Tuple = name.replace('''visual.positional_embedding''' , '''vision_model.embeddings.position_embedding.weight''' ) if name.startswith('''visual.transformer.resblocks''' ): __SCREAMING_SNAKE_CASE : List[Any] = name.replace('''visual.transformer.resblocks''' , '''vision_model.encoder.layers''' ) if "visual.conv1" in name: __SCREAMING_SNAKE_CASE : Any = name.replace('''visual.conv1''' , '''vision_model.embeddings.patch_embedding''' ) if "visual.ln_pre" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace('''visual.ln_pre''' , '''vision_model.pre_layernorm''' ) if "visual.ln_post" in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''visual.ln_post''' , '''vision_model.post_layernorm''' ) if "visual.proj" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''visual.proj''' , '''visual_projection.weight''' ) if "text_projection" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''text_projection''' , '''text_projection.weight''' ) # things on top if "prompts_visual_proj" in name: __SCREAMING_SNAKE_CASE : str = name.replace('''prompts_visual_proj''' , '''prompts_visual_projection''' ) if "prompts_visual_ln" in name: __SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''prompts_visual_ln''' , '''prompts_visual_layernorm''' ) # mit if name == "mit.positional_embedding": __SCREAMING_SNAKE_CASE : Any = name.replace('''positional''' , '''position''' ) if name.startswith('''mit.resblocks''' ): __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''mit.resblocks''' , '''mit.encoder.layers''' ) # prompts generator if name.startswith('''prompts_generator.norm''' ): __SCREAMING_SNAKE_CASE : Tuple = name.replace('''prompts_generator.norm''' , '''prompts_generator.layernorm''' ) return name def a__ ( snake_case , snake_case ): """simple docstring""" for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE : Tuple = orig_state_dict.pop(snake_case ) if "attn.in_proj" in key: __SCREAMING_SNAKE_CASE : Optional[Any] = key.split('''.''' ) if key.startswith('''visual''' ): __SCREAMING_SNAKE_CASE : List[Any] = key_split[3] __SCREAMING_SNAKE_CASE : Any = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = val[ :dim, : ] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : Tuple = val[ -dim:, : ] else: __SCREAMING_SNAKE_CASE : Optional[Any] = val[ :dim ] __SCREAMING_SNAKE_CASE : Tuple = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Tuple = val[ -dim: ] else: if "weight" in key: __SCREAMING_SNAKE_CASE : Tuple = val[ :dim, : ] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : str = val[ -dim:, : ] else: __SCREAMING_SNAKE_CASE : Dict = val[:dim] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Tuple = val[-dim:] elif key.startswith('''mit''' ): __SCREAMING_SNAKE_CASE : List[str] = key_split[2] __SCREAMING_SNAKE_CASE : Union[str, Any] = config.vision_config.mit_hidden_size if "weight" in key: __SCREAMING_SNAKE_CASE : str = val[:dim, :] __SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] __SCREAMING_SNAKE_CASE : Optional[int] = val[-dim:, :] else: __SCREAMING_SNAKE_CASE : Any = val[:dim] __SCREAMING_SNAKE_CASE : Any = val[dim : dim * 2] __SCREAMING_SNAKE_CASE : Optional[Any] = val[-dim:] else: __SCREAMING_SNAKE_CASE : Optional[Any] = key_split[2] __SCREAMING_SNAKE_CASE : Any = config.text_config.hidden_size if "weight" in key: __SCREAMING_SNAKE_CASE : Tuple = val[:dim, :] __SCREAMING_SNAKE_CASE : int = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: __SCREAMING_SNAKE_CASE : Tuple = val[:dim] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : int = val[-dim:] else: __SCREAMING_SNAKE_CASE : int = rename_key(snake_case ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: __SCREAMING_SNAKE_CASE : int = val.T __SCREAMING_SNAKE_CASE : Union[str, Any] = val return orig_state_dict def a__ ( snake_case ): """simple docstring""" if num_frames == 8: __SCREAMING_SNAKE_CASE : List[Any] = '''eating_spaghetti_8_frames.npy''' elif num_frames == 16: __SCREAMING_SNAKE_CASE : Tuple = '''eating_spaghetti.npy''' elif num_frames == 32: __SCREAMING_SNAKE_CASE : Dict = '''eating_spaghetti_32_frames.npy''' __SCREAMING_SNAKE_CASE : List[str] = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename=snake_case , repo_type='''dataset''' , ) __SCREAMING_SNAKE_CASE : int = np.load(snake_case ) return list(snake_case ) def a__ ( snake_case , snake_case=None , snake_case=False ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = { # fully supervised kinetics-400 checkpoints '''xclip-base-patch32''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth''', '''xclip-base-patch32-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth''' ), '''xclip-base-patch16''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth''', '''xclip-base-patch16-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth''' ), '''xclip-large-patch14''': '''https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb''', '''xclip-large-patch14-16-frames''': '''https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f''', # fully supervised kinetics-600 checkpoints '''xclip-base-patch16-kinetics-600''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth''' ), '''xclip-base-patch16-kinetics-600-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth''' ), '''xclip-large-patch14-kinetics-600''': '''https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be''', # few shot '''xclip-base-patch16-hmdb-2-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth''' ), '''xclip-base-patch16-hmdb-4-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth''' ), '''xclip-base-patch16-hmdb-8-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth''' ), '''xclip-base-patch16-hmdb-16-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth''' ), '''xclip-base-patch16-ucf-2-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth''' ), '''xclip-base-patch16-ucf-4-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth''' ), '''xclip-base-patch16-ucf-8-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth''' ), '''xclip-base-patch16-ucf-16-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth''' ), # zero shot '''xclip-base-patch16-zero-shot''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth''', } __SCREAMING_SNAKE_CASE : Optional[Any] = model_to_url[model_name] __SCREAMING_SNAKE_CASE : Any = 8 if "16-frames" in model_name: __SCREAMING_SNAKE_CASE : Optional[int] = 16 elif "shot" in model_name: __SCREAMING_SNAKE_CASE : Optional[Any] = 32 __SCREAMING_SNAKE_CASE : List[str] = get_xclip_config(snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Tuple = XCLIPModel(snake_case ) model.eval() if "drive" in checkpoint_url: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''pytorch_model.bin''' gdown.cached_download(snake_case , snake_case , quiet=snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(snake_case , map_location='''cpu''' )['''model'''] else: __SCREAMING_SNAKE_CASE : str = torch.hub.load_state_dict_from_url(snake_case )['''model'''] __SCREAMING_SNAKE_CASE : List[Any] = convert_state_dict(snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = XCLIPModel(snake_case ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Any = model.load_state_dict(snake_case , strict=snake_case ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() __SCREAMING_SNAKE_CASE : Any = 336 if model_name == '''xclip-large-patch14-16-frames''' else 224 __SCREAMING_SNAKE_CASE : str = VideoMAEImageProcessor(size=snake_case ) __SCREAMING_SNAKE_CASE : int = CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32''' ) __SCREAMING_SNAKE_CASE : Optional[int] = CLIPTokenizerFast.from_pretrained('''openai/clip-vit-base-patch32''' ) __SCREAMING_SNAKE_CASE : List[Any] = XCLIPProcessor(image_processor=snake_case , tokenizer=snake_case ) __SCREAMING_SNAKE_CASE : Dict = prepare_video(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = processor( text=['''playing sports''', '''eating spaghetti''', '''go shopping'''] , videos=snake_case , return_tensors='''pt''' , padding=snake_case ) print('''Shape of pixel values:''' , inputs.pixel_values.shape ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Optional[Any] = model(**snake_case ) # Verify outputs __SCREAMING_SNAKE_CASE : Dict = outputs.logits_per_video __SCREAMING_SNAKE_CASE : Tuple = logits_per_video.softmax(dim=1 ) print('''Probs:''' , snake_case ) # kinetics-400 if model_name == "xclip-base-patch32": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0.0019, 0.9951, 0.0030]] ) elif model_name == "xclip-base-patch32-16-frames": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[7.0999E-04, 9.9883E-01, 4.5580E-04]] ) elif model_name == "xclip-base-patch16": __SCREAMING_SNAKE_CASE : Dict = torch.tensor([[0.0083, 0.9681, 0.0236]] ) elif model_name == "xclip-base-patch16-16-frames": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[7.6937E-04, 9.9728E-01, 1.9473E-03]] ) elif model_name == "xclip-large-patch14": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0.0062, 0.9864, 0.0075]] ) elif model_name == "xclip-large-patch14-16-frames": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[3.3877E-04, 9.9937E-01, 2.8888E-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0.0555, 0.8914, 0.0531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[3.8554E-04, 9.9929E-01, 3.2754E-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([[0.0036, 0.9920, 0.0045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": __SCREAMING_SNAKE_CASE : str = torch.tensor([[7.1890E-06, 9.9994E-01, 5.6559E-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": __SCREAMING_SNAKE_CASE : int = torch.tensor([[1.0320E-05, 9.9993E-01, 6.2435E-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[4.1377E-06, 9.9990E-01, 9.8386E-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": __SCREAMING_SNAKE_CASE : Dict = torch.tensor([[4.1347E-05, 9.9962E-01, 3.3411E-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[8.5857E-05, 9.9928E-01, 6.3291E-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[8.5857E-05, 9.9928E-01, 6.3291E-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0.0027, 0.9904, 0.0070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[9.8219E-04, 9.9593E-01, 3.0863E-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[3.5082E-04, 9.9785E-01, 1.7966E-03]] ) else: raise ValueError(F'''Model name {model_name} not supported''' ) assert torch.allclose(snake_case , snake_case , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(snake_case ) if push_to_hub: print('''Pushing model, processor and slow tokenizer files to the hub...''' ) model.push_to_hub(snake_case , organization='''nielsr''' ) processor.push_to_hub(snake_case , organization='''nielsr''' ) slow_tokenizer.push_to_hub(snake_case , organization='''nielsr''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""xclip-base-patch32""", type=str, help="""Name of the model.""", ) 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 or not to push the converted model to the 🤗 hub.""" ) lowercase_ = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
74
1
from ..utils import DummyObject, requires_backends class __UpperCamelCase ( metaclass=lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''transformers''', '''torch''', '''note_seq'''] def __init__( self : Optional[Any] , *_A : Union[str, Any] , **_A : Tuple ): """simple docstring""" requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def UpperCAmelCase__ ( cls : int , *_A : int , **_A : Optional[Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def UpperCAmelCase__ ( cls : Any , *_A : Optional[int] , **_A : Tuple ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
74
from pathlib import Path import fire def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = Path(snake_case ) __SCREAMING_SNAKE_CASE : Dict = Path(snake_case ) dest_dir.mkdir(exist_ok=snake_case ) for path in src_dir.iterdir(): __SCREAMING_SNAKE_CASE : Union[str, Any] = [x.rstrip() for x in list(path.open().readlines() )][:n] __SCREAMING_SNAKE_CASE : Tuple = dest_dir.joinpath(path.name ) print(snake_case ) dest_path.open('''w''' ).write('''\n'''.join(snake_case ) ) if __name__ == "__main__": fire.Fire(minify)
74
1
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg''' __SCREAMING_SNAKE_CASE : int = Image.open(requests.get(snake_case , stream=snake_case ).raw ).convert('''RGB''' ) __SCREAMING_SNAKE_CASE : Optional[int] = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) __SCREAMING_SNAKE_CASE : Any = transform(snake_case ).unsqueeze(0 ).to(snake_case ) return image def a__ ( snake_case ): """simple docstring""" if "visual_encoder" in key: __SCREAMING_SNAKE_CASE : Dict = re.sub('''visual_encoder*''' , '''vision_model.encoder''' , snake_case ) if "blocks" in key: __SCREAMING_SNAKE_CASE : Tuple = re.sub(R'''blocks''' , '''layers''' , snake_case ) if "attn" in key: __SCREAMING_SNAKE_CASE : int = re.sub(R'''attn''' , '''self_attn''' , snake_case ) if "norm1" in key: __SCREAMING_SNAKE_CASE : Optional[Any] = re.sub(R'''norm1''' , '''layer_norm1''' , snake_case ) if "norm2" in key: __SCREAMING_SNAKE_CASE : str = re.sub(R'''norm2''' , '''layer_norm2''' , snake_case ) if "encoder.norm" in key: __SCREAMING_SNAKE_CASE : str = re.sub(R'''encoder.norm''' , '''post_layernorm''' , snake_case ) if "encoder.patch_embed.proj" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = re.sub(R'''encoder.patch_embed.proj''' , '''embeddings.patch_embedding''' , snake_case ) if "encoder.pos_embed" in key: __SCREAMING_SNAKE_CASE : Any = re.sub(R'''encoder.pos_embed''' , '''embeddings.position_embedding''' , snake_case ) if "encoder.cls_token" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = re.sub(R'''encoder.cls_token''' , '''embeddings.class_embedding''' , snake_case ) if "self_attn" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = re.sub(R'''self_attn.proj''' , '''self_attn.projection''' , snake_case ) return key @torch.no_grad() def a__ ( snake_case , snake_case=None ): """simple docstring""" if config_path is not None: __SCREAMING_SNAKE_CASE : List[str] = BlipConfig.from_pretrained(snake_case ) else: __SCREAMING_SNAKE_CASE : Tuple = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) __SCREAMING_SNAKE_CASE : Optional[Any] = BlipForConditionalGeneration(snake_case ).eval() __SCREAMING_SNAKE_CASE : Tuple = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth''' __SCREAMING_SNAKE_CASE : Optional[Any] = blip_decoder(pretrained=snake_case , image_size=384 , vit='''base''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pt_model.eval() __SCREAMING_SNAKE_CASE : Tuple = pt_model.state_dict() for key in modified_state_dict.copy(): __SCREAMING_SNAKE_CASE : List[str] = modified_state_dict.pop(snake_case ) __SCREAMING_SNAKE_CASE : int = rename_key(snake_case ) __SCREAMING_SNAKE_CASE : Optional[Any] = value hf_model.load_state_dict(snake_case ) __SCREAMING_SNAKE_CASE : int = 384 __SCREAMING_SNAKE_CASE : List[Any] = load_demo_image(image_size=snake_case , device='''cpu''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = BertTokenizer.from_pretrained('''bert-base-uncased''' ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(['''a picture of'''] ).input_ids __SCREAMING_SNAKE_CASE : Dict = hf_model.generate(snake_case , snake_case ) assert out[0].tolist() == [30_522, 1_037, 3_861, 1_997, 1_037, 2_450, 3_564, 2_006, 1_996, 3_509, 2_007, 2_014, 3_899, 102] __SCREAMING_SNAKE_CASE : Optional[Any] = hf_model.generate(snake_case ) assert out[0].tolist() == [30_522, 1_037, 2_450, 3_564, 2_006, 1_996, 3_509, 2_007, 2_014, 3_899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' __SCREAMING_SNAKE_CASE : Dict = ( '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth''' ) __SCREAMING_SNAKE_CASE : Dict = blip_vqa(pretrained=snake_case , image_size=snake_case , vit='''base''' ) vqa_model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = vqa_model.state_dict() for key in modified_state_dict.copy(): __SCREAMING_SNAKE_CASE : List[str] = modified_state_dict.pop(snake_case ) __SCREAMING_SNAKE_CASE : str = rename_key(snake_case ) __SCREAMING_SNAKE_CASE : Optional[int] = value __SCREAMING_SNAKE_CASE : str = BlipForQuestionAnswering(snake_case ) hf_vqa_model.load_state_dict(snake_case ) __SCREAMING_SNAKE_CASE : Dict = ['''How many dogs are in this image?'''] __SCREAMING_SNAKE_CASE : Any = tokenizer(snake_case , return_tensors='''pt''' ).input_ids __SCREAMING_SNAKE_CASE : Tuple = hf_vqa_model.generate(snake_case , snake_case ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth''' __SCREAMING_SNAKE_CASE : str = blip_itm(pretrained=snake_case , image_size=snake_case , vit='''base''' ) itm_model.eval() __SCREAMING_SNAKE_CASE : List[str] = itm_model.state_dict() for key in modified_state_dict.copy(): __SCREAMING_SNAKE_CASE : List[str] = modified_state_dict.pop(snake_case ) __SCREAMING_SNAKE_CASE : Tuple = rename_key(snake_case ) __SCREAMING_SNAKE_CASE : Tuple = value __SCREAMING_SNAKE_CASE : int = BlipForImageTextRetrieval(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = ['''A picture of a woman with a dog sitting in a beach'''] __SCREAMING_SNAKE_CASE : Any = tokenizer( snake_case , return_tensors='''pt''' , padding='''max_length''' , truncation=snake_case , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case ) hf_itm_model.eval() __SCREAMING_SNAKE_CASE : List[Any] = hf_itm_model(snake_case , snake_case , use_itm_head=snake_case ) __SCREAMING_SNAKE_CASE : int = hf_itm_model(snake_case , snake_case , use_itm_head=snake_case ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' ) 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("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowercase_ = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
74
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE : Tuple = DisjunctiveConstraint(_A ) self.assertTrue(isinstance(dc.token_ids , _A ) ) with self.assertRaises(_A ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_A ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_A ): DisjunctiveConstraint(_A ) # fails here def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE : Optional[Any] = DisjunctiveConstraint(_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = dc.update(1 ) __SCREAMING_SNAKE_CASE : int = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = dc.update(2 ) __SCREAMING_SNAKE_CASE : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = dc.update(3 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = stepped is True and completed is True and reset is False self.assertTrue(_A ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE : str = DisjunctiveConstraint(_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : str = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
74
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, 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 __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = KandinskyVaaImgaImgPipeline lowerCAmelCase_ = ['''image_embeds''', '''negative_image_embeds''', '''image'''] lowerCAmelCase_ = [ '''image_embeds''', '''negative_image_embeds''', '''image''', ] lowerCAmelCase_ = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] lowerCAmelCase_ = False @property def UpperCAmelCase__ ( self : str ): """simple docstring""" return 32 @property def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" return 32 @property def UpperCAmelCase__ ( self : int ): """simple docstring""" return self.time_input_dim @property def UpperCAmelCase__ ( self : int ): """simple docstring""" return self.time_input_dim * 4 @property def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" return 100 @property def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = { '''in_channels''': 4, # 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, } __SCREAMING_SNAKE_CASE : Dict = UNetaDConditionModel(**_A ) return model @property def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCAmelCase__ ( self : str ): """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_unet __SCREAMING_SNAKE_CASE : Tuple = self.dummy_movq __SCREAMING_SNAKE_CASE : Dict = { '''num_train_timesteps''': 1000, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_00_85, '''beta_end''': 0.0_12, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } __SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler(**_A ) __SCREAMING_SNAKE_CASE : Any = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def UpperCAmelCase__ ( self : Any , _A : List[str] , _A : str=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_A ) ).to(_A ) __SCREAMING_SNAKE_CASE : str = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _A ) # create init_image __SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_A ) ).to(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(_A ) ).convert('''RGB''' ).resize((256, 256) ) if str(_A ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(_A ) else: __SCREAMING_SNAKE_CASE : int = torch.Generator(device=_A ).manual_seed(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = '''cpu''' __SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Union[str, Any] = self.pipeline_class(**_A ) __SCREAMING_SNAKE_CASE : Tuple = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(**self.get_dummy_inputs(_A ) ) __SCREAMING_SNAKE_CASE : List[str] = output.images __SCREAMING_SNAKE_CASE : str = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array( [0.6_19_97_78, 0.63_98_44_06, 0.46_14_57_85, 0.62_94_49_84, 0.5_62_22_15, 0.47_30_61_32, 0.47_44_14_56, 0.4_60_76_06, 0.48_71_92_63] ) 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()}''' @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_img2img_frog.npy''' ) __SCREAMING_SNAKE_CASE : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) __SCREAMING_SNAKE_CASE : Any = '''A red cartoon frog, 4k''' __SCREAMING_SNAKE_CASE : Any = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = KandinskyVaaImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : int = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() __SCREAMING_SNAKE_CASE : Dict = pipeline( image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_A , _A )
74
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) 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""") lowercase_ = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) lowercase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''The column name of the images in the files. If not set, will try to use \'image\' or \'img\'.'''} , ) lowerCAmelCase_ = field(default=lowerCAmelCase__ , metadata={'''help''': '''A folder containing the training data.'''} ) lowerCAmelCase_ = field(default=lowerCAmelCase__ , metadata={'''help''': '''A folder containing the validation data.'''} ) lowerCAmelCase_ = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) lowerCAmelCase_ = field(default=32 , metadata={'''help''': '''The size of the square patches to use for masking.'''} ) lowerCAmelCase_ = field( default=0.6 , metadata={'''help''': '''Percentage of patches to mask.'''} , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = {} if self.train_dir is not None: __SCREAMING_SNAKE_CASE : Dict = self.train_dir if self.validation_dir is not None: __SCREAMING_SNAKE_CASE : Any = self.validation_dir __SCREAMING_SNAKE_CASE : List[Any] = data_files if data_files else None @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a ''' '''checkpoint identifier on the hub. ''' '''Don\'t set if you want to train a model from scratch.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(lowerCAmelCase__ )} , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , 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''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''Where do you want to store (cache) the pretrained models/datasets downloaded from the hub'''} , ) lowerCAmelCase_ = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) lowerCAmelCase_ = field(default=lowerCAmelCase__ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''The size (resolution) of each image. If not specified, will use `image_size` of the configuration.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''Stride to use for the encoder.'''} , ) class __UpperCamelCase : """simple docstring""" def __init__( self : Tuple , _A : Optional[int]=192 , _A : List[Any]=32 , _A : Optional[int]=4 , _A : str=0.6 ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = input_size __SCREAMING_SNAKE_CASE : List[str] = mask_patch_size __SCREAMING_SNAKE_CASE : Dict = model_patch_size __SCREAMING_SNAKE_CASE : int = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('''Input size must be divisible by mask patch size''' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('''Mask patch size must be divisible by model patch size''' ) __SCREAMING_SNAKE_CASE : Any = self.input_size // self.mask_patch_size __SCREAMING_SNAKE_CASE : Optional[Any] = self.mask_patch_size // self.model_patch_size __SCREAMING_SNAKE_CASE : int = self.rand_size**2 __SCREAMING_SNAKE_CASE : Optional[int] = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = np.random.permutation(self.token_count )[: self.mask_count] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.zeros(self.token_count , dtype=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = 1 __SCREAMING_SNAKE_CASE : List[str] = mask.reshape((self.rand_size, self.rand_size) ) __SCREAMING_SNAKE_CASE : List[Any] = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.stack([example['''pixel_values'''] for example in examples] ) __SCREAMING_SNAKE_CASE : Any = torch.stack([example['''mask'''] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def a__ ( ): """simple docstring""" # 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. __SCREAMING_SNAKE_CASE : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = 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_mim''' , snake_case , snake_case ) # 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() __SCREAMING_SNAKE_CASE : Tuple = training_args.get_process_log_level() logger.setLevel(snake_case ) transformers.utils.logging.set_verbosity(snake_case ) 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. __SCREAMING_SNAKE_CASE : Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE : Optional[int] = 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. __SCREAMING_SNAKE_CASE : Tuple = 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. __SCREAMING_SNAKE_CASE : Any = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , snake_case ) and data_args.train_val_split > 0.0: __SCREAMING_SNAKE_CASE : List[str] = ds['''train'''].train_test_split(data_args.train_val_split ) __SCREAMING_SNAKE_CASE : int = split['''train'''] __SCREAMING_SNAKE_CASE : Dict = split['''test'''] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE : List[Any] = { '''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_or_path: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(model_args.config_name_or_path , **snake_case ) elif model_args.model_name_or_path: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , **snake_case ) else: __SCREAMING_SNAKE_CASE : List[Any] = CONFIG_MAPPING[model_args.model_type]() 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}''' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(snake_case , '''decoder_type''' ): __SCREAMING_SNAKE_CASE : Any = '''simmim''' # adapt config __SCREAMING_SNAKE_CASE : str = model_args.image_size if model_args.image_size is not None else config.image_size __SCREAMING_SNAKE_CASE : int = model_args.patch_size if model_args.patch_size is not None else config.patch_size __SCREAMING_SNAKE_CASE : str = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { '''image_size''': model_args.image_size, '''patch_size''': model_args.patch_size, '''encoder_stride''': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **snake_case ) elif model_args.model_name_or_path: __SCREAMING_SNAKE_CASE : List[Any] = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **snake_case ) else: __SCREAMING_SNAKE_CASE : List[Any] = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } __SCREAMING_SNAKE_CASE : str = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: __SCREAMING_SNAKE_CASE : int = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case , 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''' ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedImageModeling.from_config(snake_case ) if training_args.do_train: __SCREAMING_SNAKE_CASE : Any = ds['''train'''].column_names else: __SCREAMING_SNAKE_CASE : int = ds['''validation'''].column_names if data_args.image_column_name is not None: __SCREAMING_SNAKE_CASE : List[Any] = data_args.image_column_name elif "image" in column_names: __SCREAMING_SNAKE_CASE : str = '''image''' elif "img" in column_names: __SCREAMING_SNAKE_CASE : List[str] = '''img''' else: __SCREAMING_SNAKE_CASE : Tuple = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py __SCREAMING_SNAKE_CASE : Any = Compose( [ Lambda(lambda snake_case : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator __SCREAMING_SNAKE_CASE : str = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(snake_case ): __SCREAMING_SNAKE_CASE : str = [transforms(snake_case ) for image in examples[image_column_name]] __SCREAMING_SNAKE_CASE : str = [mask_generator() for i in range(len(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: __SCREAMING_SNAKE_CASE : Dict = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(snake_case ) 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: __SCREAMING_SNAKE_CASE : Union[str, Any] = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(snake_case ) # Initialize our trainer __SCREAMING_SNAKE_CASE : List[str] = Trainer( model=snake_case , args=snake_case , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=snake_case , data_collator=snake_case , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE : Tuple = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE : int = last_checkpoint __SCREAMING_SNAKE_CASE : Tuple = trainer.train(resume_from_checkpoint=snake_case ) 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: __SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.evaluate() trainer.log_metrics('''eval''' , snake_case ) trainer.save_metrics('''eval''' , snake_case ) # Write model card and (optionally) push to hub __SCREAMING_SNAKE_CASE : Optional[Any] = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''masked-image-modeling''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-image-modeling'''], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case ) else: trainer.create_model_card(**snake_case ) if __name__ == "__main__": main()
74
1
import os def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(os.path.dirname(snake_case ) , '''num.txt''' ) with open(snake_case ) as file_hand: return str(sum(int(snake_case ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
74
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_ = { """facebook/data2vec-vision-base-ft""": ( """https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json""" ), } class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = '''data2vec-vision''' def __init__( self : Optional[int] , _A : List[Any]=768 , _A : Any=12 , _A : str=12 , _A : Union[str, Any]=3072 , _A : Union[str, Any]="gelu" , _A : List[Any]=0.0 , _A : Dict=0.0 , _A : Dict=0.02 , _A : Any=1e-12 , _A : Optional[Any]=224 , _A : Union[str, Any]=16 , _A : Tuple=3 , _A : List[Any]=False , _A : List[str]=False , _A : Dict=False , _A : Dict=False , _A : Any=0.1 , _A : List[str]=0.1 , _A : Dict=True , _A : Dict=[3, 5, 7, 11] , _A : Union[str, Any]=[1, 2, 3, 6] , _A : Optional[Any]=True , _A : Any=0.4 , _A : List[str]=256 , _A : Any=1 , _A : Any=False , _A : Union[str, Any]=255 , **_A : Tuple , ): """simple docstring""" super().__init__(**_A ) __SCREAMING_SNAKE_CASE : Any = hidden_size __SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Tuple = num_attention_heads __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Tuple = hidden_act __SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps __SCREAMING_SNAKE_CASE : Any = image_size __SCREAMING_SNAKE_CASE : Optional[int] = patch_size __SCREAMING_SNAKE_CASE : Any = num_channels __SCREAMING_SNAKE_CASE : List[str] = use_mask_token __SCREAMING_SNAKE_CASE : List[Any] = use_absolute_position_embeddings __SCREAMING_SNAKE_CASE : Dict = use_relative_position_bias __SCREAMING_SNAKE_CASE : str = use_shared_relative_position_bias __SCREAMING_SNAKE_CASE : Union[str, Any] = layer_scale_init_value __SCREAMING_SNAKE_CASE : str = drop_path_rate __SCREAMING_SNAKE_CASE : Tuple = use_mean_pooling # decode head attributes (semantic segmentation) __SCREAMING_SNAKE_CASE : str = out_indices __SCREAMING_SNAKE_CASE : List[str] = pool_scales # auxiliary head attributes (semantic segmentation) __SCREAMING_SNAKE_CASE : Tuple = use_auxiliary_head __SCREAMING_SNAKE_CASE : Optional[Any] = auxiliary_loss_weight __SCREAMING_SNAKE_CASE : Union[str, Any] = auxiliary_channels __SCREAMING_SNAKE_CASE : List[Any] = auxiliary_num_convs __SCREAMING_SNAKE_CASE : Optional[Any] = auxiliary_concat_input __SCREAMING_SNAKE_CASE : Any = semantic_loss_ignore_index class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = version.parse('''1.11''' ) @property def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return 1e-4
74
1
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import 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 ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase : """simple docstring""" def __init__( self : Dict , _A : str , _A : Optional[int]=13 , _A : List[Any]=7 , _A : Tuple=True , _A : Any=True , _A : List[str]=True , _A : Any=True , _A : Optional[Any]=99 , _A : int=16 , _A : str=36 , _A : Dict=6 , _A : Optional[int]=6 , _A : int=6 , _A : Dict=37 , _A : List[str]="gelu" , _A : Tuple=0.1 , _A : str=0.1 , _A : Tuple=512 , _A : Optional[Any]=16 , _A : Any=2 , _A : Optional[Any]=0.02 , _A : Tuple=3 , _A : Optional[int]=4 , _A : Any=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = parent __SCREAMING_SNAKE_CASE : Any = batch_size __SCREAMING_SNAKE_CASE : Dict = seq_length __SCREAMING_SNAKE_CASE : List[Any] = is_training __SCREAMING_SNAKE_CASE : Any = use_input_mask __SCREAMING_SNAKE_CASE : List[Any] = use_token_type_ids __SCREAMING_SNAKE_CASE : Dict = use_labels __SCREAMING_SNAKE_CASE : Optional[int] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = embedding_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : Dict = num_hidden_layers __SCREAMING_SNAKE_CASE : List[Any] = num_hidden_groups __SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : str = hidden_act __SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = type_sequence_label_size __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : Optional[int] = num_labels __SCREAMING_SNAKE_CASE : List[Any] = num_choices __SCREAMING_SNAKE_CASE : Tuple = scope def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : Tuple = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : str = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE : Dict = None __SCREAMING_SNAKE_CASE : Union[str, Any] = None __SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: __SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return AlbertConfig( 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 , num_hidden_groups=self.num_hidden_groups , ) def UpperCAmelCase__ ( self : Dict , _A : Optional[int] , _A : Dict , _A : str , _A : Union[str, Any] , _A : Optional[Any] , _A : Optional[Any] , _A : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = AlbertModel(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : List[Any] = model(_A , attention_mask=_A , token_type_ids=_A ) __SCREAMING_SNAKE_CASE : str = model(_A , token_type_ids=_A ) __SCREAMING_SNAKE_CASE : int = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase__ ( self : Optional[Any] , _A : str , _A : Optional[int] , _A : Dict , _A : List[str] , _A : List[str] , _A : Any , _A : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = AlbertForPreTraining(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , sentence_order_label=_A , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def UpperCAmelCase__ ( self : Dict , _A : Optional[int] , _A : List[str] , _A : Union[str, Any] , _A : Optional[Any] , _A : Any , _A : List[str] , _A : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = AlbertForMaskedLM(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : int = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self : Tuple , _A : Any , _A : Tuple , _A : Union[str, Any] , _A : Tuple , _A : int , _A : Optional[int] , _A : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = AlbertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = model( _A , attention_mask=_A , token_type_ids=_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 : List[str] , _A : List[str] , _A : str , _A : int , _A : Any , _A : Optional[Any] , _A : Optional[int] , _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.num_labels __SCREAMING_SNAKE_CASE : Optional[int] = AlbertForSequenceClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : List[str] , _A : Optional[int] , _A : Optional[Any] , _A : Union[str, Any] , _A : List[str] , _A : Dict , _A : Optional[int] , _A : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.num_labels __SCREAMING_SNAKE_CASE : str = AlbertForTokenClassification(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : int = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[int] , _A : List[str] , _A : List[str] , _A : Tuple , _A : Optional[Any] , _A : Optional[int] , _A : Any , _A : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.num_choices __SCREAMING_SNAKE_CASE : Union[str, Any] = AlbertForMultipleChoice(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[Any] = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ( __SCREAMING_SNAKE_CASE ), ) : List[str] = config_and_inputs __SCREAMING_SNAKE_CASE : Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase_ = ( { '''feature-extraction''': AlbertModel, '''fill-mask''': AlbertForMaskedLM, '''question-answering''': AlbertForQuestionAnswering, '''text-classification''': AlbertForSequenceClassification, '''token-classification''': AlbertForTokenClassification, '''zero-shot''': AlbertForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = True def UpperCAmelCase__ ( self : int , _A : Optional[int] , _A : List[str] , _A : int=False ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class in get_values(_A ): __SCREAMING_SNAKE_CASE : Dict = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_A ) __SCREAMING_SNAKE_CASE : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) return inputs_dict def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = AlbertModelTester(self ) __SCREAMING_SNAKE_CASE : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_A ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE : str = type self.model_tester.create_and_check_model(*_A ) @slow def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Tuple = AlbertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_torch class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = AlbertModel.from_pretrained('''albert-base-v2''' ) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(_A , attention_mask=_A )[0] __SCREAMING_SNAKE_CASE : List[Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) )
74
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[str] , _A : Optional[int] , _A : Optional[Any]=13 , _A : List[Any]=7 , _A : List[str]=True , _A : Dict=True , _A : Tuple=False , _A : Union[str, Any]=True , _A : List[str]=99 , _A : Union[str, Any]=32 , _A : str=5 , _A : Union[str, Any]=4 , _A : int=37 , _A : int="gelu" , _A : Tuple=0.1 , _A : Dict=0.1 , _A : Optional[Any]=512 , _A : str=16 , _A : List[Any]=2 , _A : List[Any]=0.02 , _A : Any=3 , _A : Optional[int]=4 , _A : Optional[int]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : str = seq_length __SCREAMING_SNAKE_CASE : int = is_training __SCREAMING_SNAKE_CASE : Union[str, Any] = use_input_mask __SCREAMING_SNAKE_CASE : str = use_token_type_ids __SCREAMING_SNAKE_CASE : Any = use_labels __SCREAMING_SNAKE_CASE : Any = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : Any = num_hidden_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads __SCREAMING_SNAKE_CASE : List[str] = intermediate_size __SCREAMING_SNAKE_CASE : List[str] = hidden_act __SCREAMING_SNAKE_CASE : int = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings __SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : List[Any] = num_labels __SCREAMING_SNAKE_CASE : List[Any] = num_choices __SCREAMING_SNAKE_CASE : Union[str, Any] = scope def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : Any = None __SCREAMING_SNAKE_CASE : Union[str, Any] = None __SCREAMING_SNAKE_CASE : int = None if self.use_labels: __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Optional[int] , _A : int , _A : Union[str, Any] , _A : List[str] , _A : Dict , _A : Dict , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Tuple , _A : Dict , _A : Tuple , _A : str , _A : Optional[int] , _A : List[str] , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForMaskedLM(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = 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 : Dict , _A : Optional[Any] , _A : Optional[Any] , _A : Union[str, Any] , _A : Optional[Any] , _A : str , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : int = 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 : Dict , _A : List[str] , _A : Tuple , _A : str , _A : Tuple , _A : Optional[int] , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels __SCREAMING_SNAKE_CASE : List[Any] = DistilBertForSequenceClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : List[str] , _A : int , _A : List[Any] , _A : Any , _A : Any , _A : str , _A : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForTokenClassification(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = 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 : Dict , _A : Optional[int] , _A : int , _A : Optional[int] , _A : List[Any] , _A : int , _A : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.num_choices __SCREAMING_SNAKE_CASE : int = DistilBertForMultipleChoice(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Any = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[Any] = model( _A , attention_mask=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ((__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE)) : List[Any] = config_and_inputs __SCREAMING_SNAKE_CASE : Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) lowerCAmelCase_ = ( { '''feature-extraction''': DistilBertModel, '''fill-mask''': DistilBertForMaskedLM, '''question-answering''': DistilBertForQuestionAnswering, '''text-classification''': DistilBertForSequenceClassification, '''token-classification''': DistilBertForTokenClassification, '''zero-shot''': DistilBertForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = True def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = DistilBertModelTester(self ) __SCREAMING_SNAKE_CASE : List[str] = ConfigTester(self , config_class=_A , dim=37 ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*_A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*_A ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*_A ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*_A ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @slow @require_torch_gpu def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return __SCREAMING_SNAKE_CASE : Dict = True __SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(config=_A ) __SCREAMING_SNAKE_CASE : int = self._prepare_for_class(_A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = torch.jit.trace( _A , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_A , os.path.join(_A , '''traced_model.pt''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.jit.load(os.path.join(_A , '''traced_model.pt''' ) , map_location=_A ) loaded(inputs_dict['''input_ids'''].to(_A ) , inputs_dict['''attention_mask'''].to(_A ) ) @require_torch class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel.from_pretrained('''distilbert-base-uncased''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A , attention_mask=_A )[0] __SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _A ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) )
74
1
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MobileBertTokenizer lowerCAmelCase_ = MobileBertTokenizerFast lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = filter_non_english lowerCAmelCase_ = '''google/mobilebert-uncased''' def UpperCAmelCase__ ( self : Dict ): """simple docstring""" super().setUp() __SCREAMING_SNAKE_CASE : List[str] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : int = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def UpperCAmelCase__ ( self : Tuple , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : List[str] = '''unwanted, running''' return input_text, output_text def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase__ ( self : int ): """simple docstring""" if not self.test_rust_tokenizer: return __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : str = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Any = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : str = tokenizer.encode(_A ) __SCREAMING_SNAKE_CASE : Any = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) # With lower casing __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer(do_lower_case=_A ) __SCREAMING_SNAKE_CASE : List[str] = self.get_rust_tokenizer(do_lower_case=_A ) __SCREAMING_SNAKE_CASE : List[str] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : int = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BasicTokenizer(do_lower_case=_A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] __SCREAMING_SNAKE_CASE : Dict = {} for i, token in enumerate(_A ): __SCREAMING_SNAKE_CASE : List[str] = i __SCREAMING_SNAKE_CASE : str = WordpieceTokenizer(vocab=_A , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def UpperCAmelCase__ ( self : str ): """simple docstring""" self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(_A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(_A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode('''sequence builders''' , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Any = tokenizer.build_inputs_with_special_tokens(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : str = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_r.encode_plus( _A , return_attention_mask=_A , return_token_type_ids=_A , return_offsets_mapping=_A , add_special_tokens=_A , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_r.do_lower_case if hasattr(_A , '''do_lower_case''' ) else False __SCREAMING_SNAKE_CASE : Optional[Any] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = ['''的''', '''人''', '''有'''] __SCREAMING_SNAKE_CASE : int = ''''''.join(_A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : int = self.tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : int = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer_p.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer_r.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_r.convert_ids_to_tokens(_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = False __SCREAMING_SNAKE_CASE : Any = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Dict = tokenizer_r.convert_ids_to_tokens(_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE : List[Any] = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(_A ) ] self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A )
74
import logging import os import threading import time try: import warnings except ImportError: lowercase_ = None try: import msvcrt except ImportError: lowercase_ = None try: import fcntl except ImportError: lowercase_ = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowercase_ = OSError # Data # ------------------------------------------------ lowercase_ = [ """Timeout""", """BaseFileLock""", """WindowsFileLock""", """UnixFileLock""", """SoftFileLock""", """FileLock""", ] lowercase_ = """3.0.12""" lowercase_ = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE : Optional[Any] = _logger or logging.getLogger(__name__ ) return _logger class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[Any] , _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = lock_file return None def __str__( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = F'''The file lock \'{self.lock_file}\' could not be acquired.''' return temp class __UpperCamelCase : """simple docstring""" def __init__( self : Optional[Any] , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = lock return None def __enter__( self : Any ): """simple docstring""" return self.lock def __exit__( self : str , _A : Any , _A : int , _A : Any ): """simple docstring""" self.lock.release() return None class __UpperCamelCase : """simple docstring""" def __init__( self : Any , _A : int , _A : Optional[int]=-1 , _A : List[Any]=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE : Optional[Any] = self.hash_filename_if_too_long(_A , _A ) # The path to the lock file. __SCREAMING_SNAKE_CASE : Tuple = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE : str = None # The default timeout value. __SCREAMING_SNAKE_CASE : Any = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE : int = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE : int = 0 return None @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : Tuple , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = float(_A ) return None def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Tuple , _A : List[Any]=None , _A : Optional[Any]=0.05 ): """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE : Optional[int] = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE : Tuple = id(self ) __SCREAMING_SNAKE_CASE : Any = self._lock_file __SCREAMING_SNAKE_CASE : Union[str, Any] = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(F'''Attempting to acquire lock {lock_id} on {lock_filename}''' ) self._acquire() if self.is_locked: logger().debug(F'''Lock {lock_id} acquired on {lock_filename}''' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(F'''Timeout on acquiring lock {lock_id} on {lock_filename}''' ) raise Timeout(self._lock_file ) else: logger().debug( F'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...''' ) time.sleep(_A ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE : Optional[Any] = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : int , _A : List[str]=False ): """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE : Optional[int] = id(self ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self._lock_file logger().debug(F'''Attempting to release lock {lock_id} on {lock_filename}''' ) self._release() __SCREAMING_SNAKE_CASE : int = 0 logger().debug(F'''Lock {lock_id} released on {lock_filename}''' ) return None def __enter__( self : int ): """simple docstring""" self.acquire() return self def __exit__( self : Optional[int] , _A : List[str] , _A : List[Any] , _A : int ): """simple docstring""" self.release() return None def __del__( self : int ): """simple docstring""" self.release(force=_A ) return None def UpperCAmelCase__ ( self : Optional[int] , _A : str , _A : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = os.path.basename(_A ) if len(_A ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE : Tuple = os.path.dirname(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = str(hash(_A ) ) __SCREAMING_SNAKE_CASE : Optional[int] = filename[: max_length - len(_A ) - 8] + '''...''' + hashed_filename + '''.lock''' return os.path.join(_A , _A ) else: return path class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[Any] , _A : Optional[Any] , _A : List[Any]=-1 , _A : Dict=None ): """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(_A , timeout=_A , max_filename_length=_A ) __SCREAMING_SNAKE_CASE : str = '''\\\\?\\''' + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE : List[str] = os.open(self._lock_file , _A ) except OSError: pass else: try: msvcrt.locking(_A , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(_A ) else: __SCREAMING_SNAKE_CASE : str = fd return None def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self._lock_file_fd __SCREAMING_SNAKE_CASE : int = None msvcrt.locking(_A , msvcrt.LK_UNLCK , 1 ) os.close(_A ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : Tuple , _A : Optional[int] , _A : Dict=-1 , _A : str=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = os.statvfs(os.path.dirname(_A ) ).f_namemax super().__init__(_A , timeout=_A , max_filename_length=_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE : int = os.open(self._lock_file , _A ) try: fcntl.flock(_A , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(_A ) else: __SCREAMING_SNAKE_CASE : int = fd return None def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self._lock_file_fd __SCREAMING_SNAKE_CASE : Any = None fcntl.flock(_A , fcntl.LOCK_UN ) os.close(_A ) return None class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE : Optional[Any] = os.open(self._lock_file , _A ) except OSError: pass else: __SCREAMING_SNAKE_CASE : List[str] = fd return None def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE : Optional[Any] = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowercase_ = None if msvcrt: lowercase_ = WindowsFileLock elif fcntl: lowercase_ = UnixFileLock else: lowercase_ = SoftFileLock if warnings is not None: warnings.warn("""only soft file lock is available""")
74
1
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("""1.0.0a"""): raise Exception("""requires fairseq >= 1.0.0a""") logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = """Hello world! cécé herlolip""" def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = FairseqRobertaModel.from_pretrained(snake_case ) roberta.eval() # disable dropout __SCREAMING_SNAKE_CASE : Dict = roberta.model.encoder.sentence_encoder __SCREAMING_SNAKE_CASE : str = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: __SCREAMING_SNAKE_CASE : Tuple = roberta.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print('''Our RoBERTa config:''' , snake_case ) __SCREAMING_SNAKE_CASE : Any = XLMRobertaXLForSequenceClassification(snake_case ) if classification_head else XLMRobertaXLForMaskedLM(snake_case ) model.eval() # Now let's copy all the weights. # Embeddings __SCREAMING_SNAKE_CASE : Union[str, Any] = roberta_sent_encoder.embed_tokens.weight __SCREAMING_SNAKE_CASE : Dict = roberta_sent_encoder.embed_positions.weight __SCREAMING_SNAKE_CASE : Optional[int] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. __SCREAMING_SNAKE_CASE : Dict = roberta_sent_encoder.layer_norm.weight __SCREAMING_SNAKE_CASE : Tuple = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer __SCREAMING_SNAKE_CASE : BertLayer = model.roberta.encoder.layer[i] __SCREAMING_SNAKE_CASE : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] __SCREAMING_SNAKE_CASE : RobertaAttention = layer.attention __SCREAMING_SNAKE_CASE : Dict = roberta_layer.self_attn_layer_norm.weight __SCREAMING_SNAKE_CASE : Optional[int] = roberta_layer.self_attn_layer_norm.bias # self attention __SCREAMING_SNAKE_CASE : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = roberta_layer.self_attn.q_proj.weight __SCREAMING_SNAKE_CASE : Any = roberta_layer.self_attn.q_proj.bias __SCREAMING_SNAKE_CASE : Union[str, Any] = roberta_layer.self_attn.k_proj.weight __SCREAMING_SNAKE_CASE : List[Any] = roberta_layer.self_attn.k_proj.bias __SCREAMING_SNAKE_CASE : str = roberta_layer.self_attn.v_proj.weight __SCREAMING_SNAKE_CASE : Any = roberta_layer.self_attn.v_proj.bias # self-attention output __SCREAMING_SNAKE_CASE : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape __SCREAMING_SNAKE_CASE : List[Any] = roberta_layer.self_attn.out_proj.weight __SCREAMING_SNAKE_CASE : Union[str, Any] = roberta_layer.self_attn.out_proj.bias # this one is final layer norm __SCREAMING_SNAKE_CASE : Tuple = roberta_layer.final_layer_norm.weight __SCREAMING_SNAKE_CASE : Dict = roberta_layer.final_layer_norm.bias # intermediate __SCREAMING_SNAKE_CASE : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape __SCREAMING_SNAKE_CASE : str = roberta_layer.fca.weight __SCREAMING_SNAKE_CASE : List[Any] = roberta_layer.fca.bias # output __SCREAMING_SNAKE_CASE : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape __SCREAMING_SNAKE_CASE : int = roberta_layer.fca.weight __SCREAMING_SNAKE_CASE : Optional[Any] = roberta_layer.fca.bias # end of layer if classification_head: __SCREAMING_SNAKE_CASE : Any = roberta.model.classification_heads['''mnli'''].dense.weight __SCREAMING_SNAKE_CASE : int = roberta.model.classification_heads['''mnli'''].dense.bias __SCREAMING_SNAKE_CASE : List[str] = roberta.model.classification_heads['''mnli'''].out_proj.weight __SCREAMING_SNAKE_CASE : str = roberta.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head __SCREAMING_SNAKE_CASE : Union[str, Any] = roberta.model.encoder.lm_head.dense.weight __SCREAMING_SNAKE_CASE : int = roberta.model.encoder.lm_head.dense.bias __SCREAMING_SNAKE_CASE : int = roberta.model.encoder.lm_head.layer_norm.weight __SCREAMING_SNAKE_CASE : int = roberta.model.encoder.lm_head.layer_norm.bias __SCREAMING_SNAKE_CASE : Dict = roberta.model.encoder.lm_head.weight __SCREAMING_SNAKE_CASE : Any = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. __SCREAMING_SNAKE_CASE : torch.Tensor = roberta.encode(snake_case ).unsqueeze(0 ) # batch of size 1 __SCREAMING_SNAKE_CASE : str = model(snake_case )[0] if classification_head: __SCREAMING_SNAKE_CASE : List[str] = roberta.model.classification_heads['''mnli'''](roberta.extract_features(snake_case ) ) else: __SCREAMING_SNAKE_CASE : List[Any] = roberta.model(snake_case )[0] print(our_output.shape , their_output.shape ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(F'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 __SCREAMING_SNAKE_CASE : Dict = torch.allclose(snake_case , snake_case , atol=1E-3 ) print('''Do both models output the same tensors?''' , '''🔥''' if success else '''💩''' ) if not success: raise Exception('''Something went wRoNg''' ) pathlib.Path(snake_case ).mkdir(parents=snake_case , exist_ok=snake_case ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(snake_case ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--roberta_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head.""" ) lowercase_ = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
74
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup lowercase_ = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : Optional[Any] , **_A : Dict ): """simple docstring""" requires_backends(self , ['''bs4'''] ) super().__init__(**_A ) def UpperCAmelCase__ ( self : Optional[int] , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = [] __SCREAMING_SNAKE_CASE : Any = [] __SCREAMING_SNAKE_CASE : Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag __SCREAMING_SNAKE_CASE : Optional[int] = parent.find_all(child.name , recursive=_A ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(_A ) else next(i for i, s in enumerate(_A , 1 ) if s is child ) ) __SCREAMING_SNAKE_CASE : Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def UpperCAmelCase__ ( self : Dict , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BeautifulSoup(_A , '''html.parser''' ) __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Optional[Any] = [] __SCREAMING_SNAKE_CASE : int = [] for element in html_code.descendants: if type(_A ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue __SCREAMING_SNAKE_CASE : List[Any] = html.unescape(_A ).strip() if not text_in_this_tag: continue all_doc_strings.append(_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = self.xpath_soup(_A ) stringaxtag_seq.append(_A ) stringaxsubs_seq.append(_A ) if len(_A ) != len(_A ): raise ValueError('''Number of doc strings and xtags does not correspond''' ) if len(_A ) != len(_A ): raise ValueError('''Number of doc strings and xsubs does not correspond''' ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def UpperCAmelCase__ ( self : int , _A : Tuple , _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = '''''' for tagname, subs in zip(_A , _A ): xpath += F'''/{tagname}''' if subs != 0: xpath += F'''[{subs}]''' return xpath def __call__( self : Optional[int] , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = False # Check that strings has a valid type if isinstance(_A , _A ): __SCREAMING_SNAKE_CASE : Any = True elif isinstance(_A , (list, tuple) ): if len(_A ) == 0 or isinstance(html_strings[0] , _A ): __SCREAMING_SNAKE_CASE : List[Any] = True if not valid_strings: raise ValueError( '''HTML strings must of type `str`, `List[str]` (batch of examples), ''' F'''but is of type {type(_A )}.''' ) __SCREAMING_SNAKE_CASE : Any = bool(isinstance(_A , (list, tuple) ) and (isinstance(html_strings[0] , _A )) ) if not is_batched: __SCREAMING_SNAKE_CASE : Dict = [html_strings] # Get nodes + xpaths __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Tuple = [] for html_string in html_strings: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_three_from_single(_A ) nodes.append(_A ) __SCREAMING_SNAKE_CASE : Dict = [] for node, tag_list, sub_list in zip(_A , _A , _A ): __SCREAMING_SNAKE_CASE : List[Any] = self.construct_xpath(_A , _A ) xpath_strings.append(_A ) xpaths.append(_A ) # return as Dict __SCREAMING_SNAKE_CASE : Optional[int] = {'''nodes''': nodes, '''xpaths''': xpaths} __SCREAMING_SNAKE_CASE : List[str] = BatchFeature(data=_A , tensor_type=_A ) return encoded_inputs
74
1
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[str] , _A : Optional[int] , _A : Optional[Any]=13 , _A : List[Any]=7 , _A : List[str]=True , _A : Dict=True , _A : Tuple=False , _A : Union[str, Any]=True , _A : List[str]=99 , _A : Union[str, Any]=32 , _A : str=5 , _A : Union[str, Any]=4 , _A : int=37 , _A : int="gelu" , _A : Tuple=0.1 , _A : Dict=0.1 , _A : Optional[Any]=512 , _A : str=16 , _A : List[Any]=2 , _A : List[Any]=0.02 , _A : Any=3 , _A : Optional[int]=4 , _A : Optional[int]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : str = seq_length __SCREAMING_SNAKE_CASE : int = is_training __SCREAMING_SNAKE_CASE : Union[str, Any] = use_input_mask __SCREAMING_SNAKE_CASE : str = use_token_type_ids __SCREAMING_SNAKE_CASE : Any = use_labels __SCREAMING_SNAKE_CASE : Any = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : Any = num_hidden_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads __SCREAMING_SNAKE_CASE : List[str] = intermediate_size __SCREAMING_SNAKE_CASE : List[str] = hidden_act __SCREAMING_SNAKE_CASE : int = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings __SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : List[Any] = num_labels __SCREAMING_SNAKE_CASE : List[Any] = num_choices __SCREAMING_SNAKE_CASE : Union[str, Any] = scope def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : Any = None __SCREAMING_SNAKE_CASE : Union[str, Any] = None __SCREAMING_SNAKE_CASE : int = None if self.use_labels: __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Optional[int] , _A : int , _A : Union[str, Any] , _A : List[str] , _A : Dict , _A : Dict , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Tuple , _A : Dict , _A : Tuple , _A : str , _A : Optional[int] , _A : List[str] , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForMaskedLM(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = 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 : Dict , _A : Optional[Any] , _A : Optional[Any] , _A : Union[str, Any] , _A : Optional[Any] , _A : str , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : int = 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 : Dict , _A : List[str] , _A : Tuple , _A : str , _A : Tuple , _A : Optional[int] , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels __SCREAMING_SNAKE_CASE : List[Any] = DistilBertForSequenceClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : List[str] , _A : int , _A : List[Any] , _A : Any , _A : Any , _A : str , _A : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForTokenClassification(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = 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 : Dict , _A : Optional[int] , _A : int , _A : Optional[int] , _A : List[Any] , _A : int , _A : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.num_choices __SCREAMING_SNAKE_CASE : int = DistilBertForMultipleChoice(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Any = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[Any] = model( _A , attention_mask=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ((__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE)) : List[Any] = config_and_inputs __SCREAMING_SNAKE_CASE : Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) lowerCAmelCase_ = ( { '''feature-extraction''': DistilBertModel, '''fill-mask''': DistilBertForMaskedLM, '''question-answering''': DistilBertForQuestionAnswering, '''text-classification''': DistilBertForSequenceClassification, '''token-classification''': DistilBertForTokenClassification, '''zero-shot''': DistilBertForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = True def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = DistilBertModelTester(self ) __SCREAMING_SNAKE_CASE : List[str] = ConfigTester(self , config_class=_A , dim=37 ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*_A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*_A ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*_A ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*_A ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @slow @require_torch_gpu def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return __SCREAMING_SNAKE_CASE : Dict = True __SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(config=_A ) __SCREAMING_SNAKE_CASE : int = self._prepare_for_class(_A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = torch.jit.trace( _A , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_A , os.path.join(_A , '''traced_model.pt''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.jit.load(os.path.join(_A , '''traced_model.pt''' ) , map_location=_A ) loaded(inputs_dict['''input_ids'''].to(_A ) , inputs_dict['''attention_mask'''].to(_A ) ) @require_torch class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel.from_pretrained('''distilbert-base-uncased''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A , attention_mask=_A )[0] __SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _A ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) )
74
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case = True ): """simple docstring""" print(F'''Converting {name}...''' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": __SCREAMING_SNAKE_CASE : Tuple = timm.create_model('''levit_128s''' , pretrained=snake_case ) else: __SCREAMING_SNAKE_CASE : Any = timm.create_model('''levit_128''' , pretrained=snake_case ) if hidden_sizes == 192: __SCREAMING_SNAKE_CASE : Dict = timm.create_model('''levit_192''' , pretrained=snake_case ) if hidden_sizes == 256: __SCREAMING_SNAKE_CASE : Optional[int] = timm.create_model('''levit_256''' , pretrained=snake_case ) if hidden_sizes == 384: __SCREAMING_SNAKE_CASE : Any = timm.create_model('''levit_384''' , pretrained=snake_case ) from_model.eval() __SCREAMING_SNAKE_CASE : str = LevitForImageClassificationWithTeacher(snake_case ).eval() __SCREAMING_SNAKE_CASE : int = OrderedDict() __SCREAMING_SNAKE_CASE : List[Any] = from_model.state_dict() __SCREAMING_SNAKE_CASE : Tuple = list(from_model.state_dict().keys() ) __SCREAMING_SNAKE_CASE : str = list(our_model.state_dict().keys() ) print(len(snake_case ) , len(snake_case ) ) for i in range(len(snake_case ) ): __SCREAMING_SNAKE_CASE : int = weights[og_keys[i]] our_model.load_state_dict(snake_case ) __SCREAMING_SNAKE_CASE : str = torch.randn((2, 3, 224, 224) ) __SCREAMING_SNAKE_CASE : Tuple = from_model(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = our_model(snake_case ).logits assert torch.allclose(snake_case , snake_case ), "The model logits don't match the original one." __SCREAMING_SNAKE_CASE : Union[str, Any] = name print(snake_case ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __SCREAMING_SNAKE_CASE : Union[str, Any] = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F'''Pushed {checkpoint_name}''' ) def a__ ( snake_case , snake_case = None , snake_case = True ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = '''imagenet-1k-id2label.json''' __SCREAMING_SNAKE_CASE : int = 1_000 __SCREAMING_SNAKE_CASE : Optional[int] = (1, num_labels) __SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' __SCREAMING_SNAKE_CASE : Optional[Any] = num_labels __SCREAMING_SNAKE_CASE : List[Any] = json.load(open(hf_hub_download(snake_case , snake_case , repo_type='''dataset''' ) , '''r''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {int(snake_case ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : str = idalabel __SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : List[str] = partial(snake_case , num_labels=snake_case , idalabel=snake_case , labelaid=snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''levit-128S''': 128, '''levit-128''': 128, '''levit-192''': 192, '''levit-256''': 256, '''levit-384''': 384, } __SCREAMING_SNAKE_CASE : Optional[int] = { '''levit-128S''': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), '''levit-128''': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), '''levit-192''': ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), '''levit-256''': ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), '''levit-384''': ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , snake_case , names_to_config[model_name] , snake_case , snake_case ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , snake_case , snake_case , snake_case , snake_case ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help="""The name of the model you wish to convert, it must be one of the supported Levit* architecture,""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""levit-dump-folder/""", type=Path, required=False, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
74
1
from __future__ import annotations from typing import Generic, TypeVar lowercase_ = TypeVar("""T""") class __UpperCamelCase ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] , _A : T ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = data __SCREAMING_SNAKE_CASE : Optional[Any] = self __SCREAMING_SNAKE_CASE : Optional[int] = 0 class __UpperCamelCase ( Generic[T] ): """simple docstring""" def __init__( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : dict[T, DisjointSetTreeNode[T]] = {} def UpperCAmelCase__ ( self : Dict , _A : T ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = DisjointSetTreeNode(_A ) def UpperCAmelCase__ ( self : Optional[Any] , _A : T ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.map[data] if elem_ref != elem_ref.parent: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_set(elem_ref.parent.data ) return elem_ref.parent def UpperCAmelCase__ ( self : Optional[Any] , _A : DisjointSetTreeNode[T] , _A : DisjointSetTreeNode[T] ): """simple docstring""" if nodea.rank > nodea.rank: __SCREAMING_SNAKE_CASE : Union[str, Any] = nodea else: __SCREAMING_SNAKE_CASE : Union[str, Any] = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def UpperCAmelCase__ ( self : str , _A : T , _A : T ): """simple docstring""" self.link(self.find_set(_A ) , self.find_set(_A ) ) class __UpperCamelCase ( Generic[T] ): """simple docstring""" def __init__( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : dict[T, dict[T, int]] = {} def UpperCAmelCase__ ( self : int , _A : T ): """simple docstring""" if node not in self.connections: __SCREAMING_SNAKE_CASE : Tuple = {} def UpperCAmelCase__ ( self : Optional[int] , _A : T , _A : T , _A : int ): """simple docstring""" self.add_node(_A ) self.add_node(_A ) __SCREAMING_SNAKE_CASE : Tuple = weight __SCREAMING_SNAKE_CASE : Union[str, Any] = weight def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = [] __SCREAMING_SNAKE_CASE : List[Any] = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda _A : x[2] ) # creating the disjoint set __SCREAMING_SNAKE_CASE : Tuple = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(_A ) # MST generation __SCREAMING_SNAKE_CASE : Optional[Any] = 0 __SCREAMING_SNAKE_CASE : Optional[Any] = 0 __SCREAMING_SNAKE_CASE : List[str] = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = edges[index] index += 1 __SCREAMING_SNAKE_CASE : Dict = disjoint_set.find_set(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = disjoint_set.find_set(_A ) if parent_u != parent_v: num_edges += 1 graph.add_edge(_A , _A , _A ) disjoint_set.union(_A , _A ) return graph
74
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase_ = { """configuration_falcon""": ["""FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FalconConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FALCON_PRETRAINED_MODEL_ARCHIVE_LIST""", """FalconForCausalLM""", """FalconModel""", """FalconPreTrainedModel""", """FalconForSequenceClassification""", """FalconForTokenClassification""", """FalconForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
74
1
import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = IFInpaintingSuperResolutionPipeline lowerCAmelCase_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} lowerCAmelCase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''} ) lowerCAmelCase_ = PipelineTesterMixin.required_optional_params - {'''latents'''} def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return self._get_superresolution_dummy_components() def UpperCAmelCase__ ( self : Any , _A : str , _A : Tuple=0 ): """simple docstring""" if str(_A ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : int = torch.manual_seed(_A ) else: __SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=_A ).manual_seed(_A ) __SCREAMING_SNAKE_CASE : Dict = floats_tensor((1, 3, 16, 16) , rng=random.Random(_A ) ).to(_A ) __SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(_A ) ).to(_A ) __SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(_A ) ).to(_A ) __SCREAMING_SNAKE_CASE : str = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''original_image''': original_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def UpperCAmelCase__ ( self : int ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def UpperCAmelCase__ ( self : str ): """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" self._test_save_load_local() def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
74
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging lowercase_ = logging.get_logger(__name__) def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = set() __SCREAMING_SNAKE_CASE : str = [] def parse_line(snake_case ): for line in fp: if isinstance(snake_case , snake_case ): __SCREAMING_SNAKE_CASE : List[Any] = line.decode('''UTF-8''' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(''' ''' ): # process a single warning and move it to `selected_warnings`. if len(snake_case ) > 0: __SCREAMING_SNAKE_CASE : List[Any] = '''\n'''.join(snake_case ) # Only keep the warnings specified in `targets` if any(F''': {x}: ''' in warning for x in targets ): selected_warnings.add(snake_case ) buffer.clear() continue else: __SCREAMING_SNAKE_CASE : int = line.strip() buffer.append(snake_case ) if from_gh: for filename in os.listdir(snake_case ): __SCREAMING_SNAKE_CASE : Any = os.path.join(snake_case , snake_case ) if not os.path.isdir(snake_case ): # read the file if filename != "warnings.txt": continue with open(snake_case ) as fp: parse_line(snake_case ) else: try: with zipfile.ZipFile(snake_case ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case ): # read the file if filename != "warnings.txt": continue with z.open(snake_case ) as fp: parse_line(snake_case ) except Exception: logger.warning( F'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' ) return selected_warnings def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = set() __SCREAMING_SNAKE_CASE : List[Any] = [os.path.join(snake_case , snake_case ) for p in os.listdir(snake_case ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(snake_case , snake_case ) ) return selected_warnings if __name__ == "__main__": def a__ ( snake_case ): """simple docstring""" return values.split(''',''' ) lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) lowercase_ = parser.parse_args() lowercase_ = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links lowercase_ = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts lowercase_ = extract_warnings(args.output_dir, args.targets) lowercase_ = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
74
1
import os import sys import unittest lowercase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) lowercase_ = os.path.join("""tests""", """models""", """bert""", """test_modeling_bert.py""") lowercase_ = os.path.join("""tests""", """models""", """blip""", """test_modeling_blip.py""") class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = get_test_to_tester_mapping(_A ) __SCREAMING_SNAKE_CASE : int = get_test_to_tester_mapping(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''BertModelTest''': '''BertModelTester'''} __SCREAMING_SNAKE_CASE : List[str] = { '''BlipModelTest''': '''BlipModelTester''', '''BlipTextImageModelTest''': '''BlipTextImageModelsModelTester''', '''BlipTextModelTest''': '''BlipTextModelTester''', '''BlipTextRetrievalModelTest''': '''BlipTextRetrievalModelTester''', '''BlipVQAModelTest''': '''BlipVQAModelTester''', '''BlipVisionModelTest''': '''BlipVisionModelTester''', } self.assertEqual(get_test_info.to_json(_A ) , _A ) self.assertEqual(get_test_info.to_json(_A ) , _A ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = get_model_to_test_mapping(_A ) __SCREAMING_SNAKE_CASE : Dict = get_model_to_test_mapping(_A ) __SCREAMING_SNAKE_CASE : Dict = { '''BertForMaskedLM''': ['''BertModelTest'''], '''BertForMultipleChoice''': ['''BertModelTest'''], '''BertForNextSentencePrediction''': ['''BertModelTest'''], '''BertForPreTraining''': ['''BertModelTest'''], '''BertForQuestionAnswering''': ['''BertModelTest'''], '''BertForSequenceClassification''': ['''BertModelTest'''], '''BertForTokenClassification''': ['''BertModelTest'''], '''BertLMHeadModel''': ['''BertModelTest'''], '''BertModel''': ['''BertModelTest'''], } __SCREAMING_SNAKE_CASE : Optional[Any] = { '''BlipForConditionalGeneration''': ['''BlipTextImageModelTest'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTest'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTest'''], '''BlipModel''': ['''BlipModelTest'''], '''BlipTextModel''': ['''BlipTextModelTest'''], '''BlipVisionModel''': ['''BlipVisionModelTest'''], } self.assertEqual(get_test_info.to_json(_A ) , _A ) self.assertEqual(get_test_info.to_json(_A ) , _A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = get_model_to_tester_mapping(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = get_model_to_tester_mapping(_A ) __SCREAMING_SNAKE_CASE : int = { '''BertForMaskedLM''': ['''BertModelTester'''], '''BertForMultipleChoice''': ['''BertModelTester'''], '''BertForNextSentencePrediction''': ['''BertModelTester'''], '''BertForPreTraining''': ['''BertModelTester'''], '''BertForQuestionAnswering''': ['''BertModelTester'''], '''BertForSequenceClassification''': ['''BertModelTester'''], '''BertForTokenClassification''': ['''BertModelTester'''], '''BertLMHeadModel''': ['''BertModelTester'''], '''BertModel''': ['''BertModelTester'''], } __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''BlipForConditionalGeneration''': ['''BlipTextImageModelsModelTester'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTester'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTester'''], '''BlipModel''': ['''BlipModelTester'''], '''BlipTextModel''': ['''BlipTextModelTester'''], '''BlipVisionModel''': ['''BlipVisionModelTester'''], } self.assertEqual(get_test_info.to_json(_A ) , _A ) self.assertEqual(get_test_info.to_json(_A ) , _A )
74
from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = 42 class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" @register_to_config def __init__( self : Dict , _A : int = 16 , _A : int = 88 , _A : Optional[int] = None , _A : Optional[int] = None , _A : int = 1 , _A : float = 0.0 , _A : int = 32 , _A : Optional[int] = None , _A : bool = False , _A : Optional[int] = None , _A : str = "geglu" , _A : bool = True , _A : bool = True , ): """simple docstring""" super().__init__() __SCREAMING_SNAKE_CASE : Dict = num_attention_heads __SCREAMING_SNAKE_CASE : Optional[int] = attention_head_dim __SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads * attention_head_dim __SCREAMING_SNAKE_CASE : Tuple = in_channels __SCREAMING_SNAKE_CASE : str = torch.nn.GroupNorm(num_groups=_A , num_channels=_A , eps=1e-6 , affine=_A ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Linear(_A , _A ) # 3. Define transformers blocks __SCREAMING_SNAKE_CASE : List[Any] = nn.ModuleList( [ BasicTransformerBlock( _A , _A , _A , dropout=_A , cross_attention_dim=_A , activation_fn=_A , attention_bias=_A , double_self_attention=_A , norm_elementwise_affine=_A , ) for d in range(_A ) ] ) __SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(_A , _A ) def UpperCAmelCase__ ( self : str , _A : Dict , _A : int=None , _A : Tuple=None , _A : Dict=None , _A : List[Any]=1 , _A : Union[str, Any]=None , _A : bool = True , ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = hidden_states.shape __SCREAMING_SNAKE_CASE : Any = batch_frames // num_frames __SCREAMING_SNAKE_CASE : Dict = hidden_states __SCREAMING_SNAKE_CASE : str = hidden_states[None, :].reshape(_A , _A , _A , _A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.norm(_A ) __SCREAMING_SNAKE_CASE : List[str] = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , _A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = self.proj_in(_A ) # 2. Blocks for block in self.transformer_blocks: __SCREAMING_SNAKE_CASE : Optional[Any] = block( _A , encoder_hidden_states=_A , timestep=_A , cross_attention_kwargs=_A , class_labels=_A , ) # 3. Output __SCREAMING_SNAKE_CASE : Any = self.proj_out(_A ) __SCREAMING_SNAKE_CASE : List[str] = ( hidden_states[None, None, :] .reshape(_A , _A , _A , _A , _A ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_states.reshape(_A , _A , _A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=_A )
74
1
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , _A : int , _A : Dict=13 , _A : Optional[int]=32 , _A : str=3 , _A : Optional[Any]=4 , _A : Optional[int]=[10, 20, 30, 40] , _A : Union[str, Any]=[2, 2, 3, 2] , _A : List[Any]=True , _A : Tuple=True , _A : List[str]=37 , _A : Optional[Any]="gelu" , _A : Union[str, Any]=10 , _A : int=0.02 , _A : int=["stage2", "stage3", "stage4"] , _A : str=[2, 3, 4] , _A : List[Any]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : List[Any] = image_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : int = num_stages __SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_sizes __SCREAMING_SNAKE_CASE : int = depths __SCREAMING_SNAKE_CASE : Tuple = is_training __SCREAMING_SNAKE_CASE : List[Any] = use_labels __SCREAMING_SNAKE_CASE : str = intermediate_size __SCREAMING_SNAKE_CASE : List[str] = hidden_act __SCREAMING_SNAKE_CASE : List[str] = num_labels __SCREAMING_SNAKE_CASE : List[str] = initializer_range __SCREAMING_SNAKE_CASE : int = out_features __SCREAMING_SNAKE_CASE : Optional[Any] = out_indices __SCREAMING_SNAKE_CASE : Tuple = scope def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_labels: __SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.num_labels ) __SCREAMING_SNAKE_CASE : List[str] = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self : Any ): """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_A , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def UpperCAmelCase__ ( self : Union[str, Any] , _A : List[Any] , _A : int , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = ConvNextVaModel(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model(_A ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCAmelCase__ ( self : Union[str, Any] , _A : List[Any] , _A : List[str] , _A : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = ConvNextVaForImageClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : Dict , _A : str , _A : Union[str, Any] , _A : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = ConvNextVaBackbone(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = model(_A ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __SCREAMING_SNAKE_CASE : str = None __SCREAMING_SNAKE_CASE : List[Any] = ConvNextVaBackbone(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = model(_A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs __SCREAMING_SNAKE_CASE : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = config_and_inputs __SCREAMING_SNAKE_CASE : List[str] = {'''pixel_values''': pixel_values, '''labels''': labels} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCAmelCase_ = ( {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = ConvNextVaModelTester(self ) __SCREAMING_SNAKE_CASE : Tuple = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=37 ) def UpperCAmelCase__ ( self : str ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ): """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_with_labels() __SCREAMING_SNAKE_CASE : int = True if model_class.__name__ in [ *get_values(_A ), *get_values(_A ), ]: continue __SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_A ) model.to(_A ) model.train() __SCREAMING_SNAKE_CASE : List[str] = self._prepare_for_class(_A , _A , return_labels=_A ) __SCREAMING_SNAKE_CASE : Tuple = model(**_A ).loss loss.backward() def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_with_labels() __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = True if ( model_class.__name__ in [*get_values(_A ), *get_values(_A )] or not model_class.supports_gradient_checkpointing ): continue __SCREAMING_SNAKE_CASE : str = model_class(_A ) model.to(_A ) model.gradient_checkpointing_enable() model.train() __SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(_A , _A , return_labels=_A ) __SCREAMING_SNAKE_CASE : Dict = model(**_A ).loss loss.backward() def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_A ) __SCREAMING_SNAKE_CASE : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : Optional[Any] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _A ) def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" def check_hidden_states_output(_A : Tuple , _A : Optional[int] , _A : Dict ): __SCREAMING_SNAKE_CASE : int = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE : Dict = model(**self._prepare_for_class(_A , _A ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(_A ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Any = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE : Any = True check_hidden_states_output(_A , _A , _A ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) @slow def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : List[str] = ConvNextVaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : List[str] = prepare_img() __SCREAMING_SNAKE_CASE : Union[str, Any] = preprocessor(images=_A , return_tensors='''pt''' ).to(_A ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_A ) # verify the logits __SCREAMING_SNAKE_CASE : str = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1e-4 ) )
74
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py lowercase_ = """src/diffusers""" lowercase_ = """.""" # This is to make sure the diffusers module imported is the one in the repo. lowercase_ = importlib.util.spec_from_file_location( """diffusers""", os.path.join(DIFFUSERS_PATH, """__init__.py"""), submodule_search_locations=[DIFFUSERS_PATH], ) lowercase_ = spec.loader.load_module() def a__ ( snake_case , snake_case ): """simple docstring""" return line.startswith(snake_case ) or len(snake_case ) <= 1 or re.search(R'''^\s*\)(\s*->.*:|:)\s*$''' , snake_case ) is not None def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = object_name.split('''.''' ) __SCREAMING_SNAKE_CASE : str = 0 # First let's find the module where our object lives. __SCREAMING_SNAKE_CASE : Any = parts[i] while i < len(snake_case ) and not os.path.isfile(os.path.join(snake_case , F'''{module}.py''' ) ): i += 1 if i < len(snake_case ): __SCREAMING_SNAKE_CASE : str = os.path.join(snake_case , parts[i] ) if i >= len(snake_case ): raise ValueError(F'''`object_name` should begin with the name of a module of diffusers but got {object_name}.''' ) with open(os.path.join(snake_case , F'''{module}.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __SCREAMING_SNAKE_CASE : Dict = f.readlines() # Now let's find the class / func in the code! __SCREAMING_SNAKE_CASE : Union[str, Any] = '''''' __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(snake_case ) and re.search(RF'''^{indent}(class|def)\s+{name}(\(|\:)''' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(snake_case ): raise ValueError(F''' {object_name} does not match any function or class in {module}.''' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). __SCREAMING_SNAKE_CASE : List[Any] = line_index while line_index < len(snake_case ) and _should_continue(lines[line_index] , snake_case ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __SCREAMING_SNAKE_CASE : Dict = lines[start_index:line_index] return "".join(snake_case ) lowercase_ = re.compile(R"""^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)""") lowercase_ = re.compile(R"""^\s*(\S+)->(\S+)(\s+.*|$)""") lowercase_ = re.compile(R"""<FILL\s+[^>]*>""") def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = code.split('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = 0 while idx < len(snake_case ) and len(lines[idx] ) == 0: idx += 1 if idx < len(snake_case ): return re.search(R'''^(\s*)\S''' , lines[idx] ).groups()[0] return "" def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = len(get_indent(snake_case ) ) > 0 if has_indent: __SCREAMING_SNAKE_CASE : List[Any] = F'''class Bla:\n{code}''' __SCREAMING_SNAKE_CASE : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=snake_case ) __SCREAMING_SNAKE_CASE : Optional[int] = black.format_str(snake_case , mode=snake_case ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = style_docstrings_in_code(snake_case ) return result[len('''class Bla:\n''' ) :] if has_indent else result def a__ ( snake_case , snake_case=False ): """simple docstring""" with open(snake_case , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __SCREAMING_SNAKE_CASE : List[str] = f.readlines() __SCREAMING_SNAKE_CASE : Optional[Any] = [] __SCREAMING_SNAKE_CASE : int = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(snake_case ): __SCREAMING_SNAKE_CASE : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = search.groups() __SCREAMING_SNAKE_CASE : int = find_code_in_diffusers(snake_case ) __SCREAMING_SNAKE_CASE : str = get_indent(snake_case ) __SCREAMING_SNAKE_CASE : Any = line_index + 1 if indent == theoretical_indent else line_index + 2 __SCREAMING_SNAKE_CASE : Dict = theoretical_indent __SCREAMING_SNAKE_CASE : Optional[int] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. __SCREAMING_SNAKE_CASE : List[Any] = True while line_index < len(snake_case ) and should_continue: line_index += 1 if line_index >= len(snake_case ): break __SCREAMING_SNAKE_CASE : Any = lines[line_index] __SCREAMING_SNAKE_CASE : Optional[Any] = _should_continue(snake_case , snake_case ) and re.search(F'''^{indent}# End copy''' , snake_case ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __SCREAMING_SNAKE_CASE : List[str] = lines[start_index:line_index] __SCREAMING_SNAKE_CASE : Dict = ''''''.join(snake_case ) # Remove any nested `Copied from` comments to avoid circular copies __SCREAMING_SNAKE_CASE : Tuple = [line for line in theoretical_code.split('''\n''' ) if _re_copy_warning.search(snake_case ) is None] __SCREAMING_SNAKE_CASE : Union[str, Any] = '''\n'''.join(snake_case ) # Before comparing, use the `replace_pattern` on the original code. if len(snake_case ) > 0: __SCREAMING_SNAKE_CASE : Union[str, Any] = replace_pattern.replace('''with''' , '''''' ).split(''',''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = [_re_replace_pattern.search(snake_case ) for p in patterns] for pattern in patterns: if pattern is None: continue __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = pattern.groups() __SCREAMING_SNAKE_CASE : str = re.sub(snake_case , snake_case , snake_case ) if option.strip() == "all-casing": __SCREAMING_SNAKE_CASE : Optional[Any] = re.sub(obja.lower() , obja.lower() , snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = re.sub(obja.upper() , obja.upper() , snake_case ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line __SCREAMING_SNAKE_CASE : Optional[Any] = blackify(lines[start_index - 1] + theoretical_code ) __SCREAMING_SNAKE_CASE : int = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: __SCREAMING_SNAKE_CASE : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] __SCREAMING_SNAKE_CASE : str = start_index + 1 if overwrite and len(snake_case ) > 0: # Warn the user a file has been modified. print(F'''Detected changes, rewriting {filename}.''' ) with open(snake_case , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(snake_case ) return diffs def a__ ( snake_case = False ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = glob.glob(os.path.join(snake_case , '''**/*.py''' ) , recursive=snake_case ) __SCREAMING_SNAKE_CASE : Tuple = [] for filename in all_files: __SCREAMING_SNAKE_CASE : int = is_copy_consistent(snake_case , snake_case ) diffs += [F'''- {filename}: copy does not match {d[0]} at line {d[1]}''' for d in new_diffs] if not overwrite and len(snake_case ) > 0: __SCREAMING_SNAKE_CASE : Optional[int] = '''\n'''.join(snake_case ) raise Exception( '''Found the following copy inconsistencies:\n''' + diff + '''\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") lowercase_ = parser.parse_args() check_copies(args.fix_and_overwrite)
74
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = 384 if "tiny" in model_name: __SCREAMING_SNAKE_CASE : Tuple = [3, 3, 9, 3] __SCREAMING_SNAKE_CASE : Union[str, Any] = [96, 192, 384, 768] if "small" in model_name: __SCREAMING_SNAKE_CASE : int = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE : List[str] = [96, 192, 384, 768] if "base" in model_name: __SCREAMING_SNAKE_CASE : Union[str, Any] = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE : List[Any] = [128, 256, 512, 1_024] __SCREAMING_SNAKE_CASE : Tuple = 512 if "large" in model_name: __SCREAMING_SNAKE_CASE : List[Any] = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE : Dict = [192, 384, 768, 1_536] __SCREAMING_SNAKE_CASE : str = 768 if "xlarge" in model_name: __SCREAMING_SNAKE_CASE : Union[str, Any] = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE : List[str] = [256, 512, 1_024, 2_048] __SCREAMING_SNAKE_CASE : str = 1_024 # set label information __SCREAMING_SNAKE_CASE : List[str] = 150 __SCREAMING_SNAKE_CASE : Tuple = '''huggingface/label-files''' __SCREAMING_SNAKE_CASE : List[Any] = '''ade20k-id2label.json''' __SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(snake_case , snake_case , repo_type='''dataset''' ) , '''r''' ) ) __SCREAMING_SNAKE_CASE : Tuple = {int(snake_case ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : Union[str, Any] = ConvNextConfig( depths=snake_case , hidden_sizes=snake_case , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) __SCREAMING_SNAKE_CASE : int = UperNetConfig( backbone_config=snake_case , auxiliary_in_channels=snake_case , num_labels=snake_case , idalabel=snake_case , labelaid=snake_case , ) return config def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = [] # fmt: off # stem rename_keys.append(('''backbone.downsample_layers.0.0.weight''', '''backbone.embeddings.patch_embeddings.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.0.bias''', '''backbone.embeddings.patch_embeddings.bias''') ) rename_keys.append(('''backbone.downsample_layers.0.1.weight''', '''backbone.embeddings.layernorm.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.1.bias''', '''backbone.embeddings.layernorm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.stages.{i}.{j}.gamma''', F'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.norm.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.norm.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((F'''backbone.downsample_layers.{i}.0.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.0.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.1.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((F'''backbone.downsample_layers.{i}.1.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((F'''backbone.norm{i}.weight''', F'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((F'''backbone.norm{i}.bias''', F'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ('''decode_head.conv_seg.weight''', '''decode_head.classifier.weight'''), ('''decode_head.conv_seg.bias''', '''decode_head.classifier.bias'''), ('''auxiliary_head.conv_seg.weight''', '''auxiliary_head.classifier.weight'''), ('''auxiliary_head.conv_seg.bias''', '''auxiliary_head.classifier.bias'''), ] ) # fmt: on return rename_keys def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = dct.pop(snake_case ) __SCREAMING_SNAKE_CASE : Optional[Any] = val def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = { '''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''', '''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''', '''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''', '''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''', '''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''', } __SCREAMING_SNAKE_CASE : Tuple = model_name_to_url[model_name] __SCREAMING_SNAKE_CASE : Dict = torch.hub.load_state_dict_from_url(snake_case , map_location='''cpu''' )['''state_dict'''] __SCREAMING_SNAKE_CASE : Dict = get_upernet_config(snake_case ) __SCREAMING_SNAKE_CASE : Dict = UperNetForSemanticSegmentation(snake_case ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __SCREAMING_SNAKE_CASE : List[Any] = state_dict.pop(snake_case ) if "bn" in key: __SCREAMING_SNAKE_CASE : Dict = key.replace('''bn''' , '''batch_norm''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = val # rename keys __SCREAMING_SNAKE_CASE : int = create_rename_keys(snake_case ) for src, dest in rename_keys: rename_key(snake_case , snake_case , snake_case ) model.load_state_dict(snake_case ) # verify on image __SCREAMING_SNAKE_CASE : Optional[Any] = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' __SCREAMING_SNAKE_CASE : Any = Image.open(requests.get(snake_case , stream=snake_case ).raw ).convert('''RGB''' ) __SCREAMING_SNAKE_CASE : Tuple = SegformerImageProcessor() __SCREAMING_SNAKE_CASE : Tuple = processor(snake_case , return_tensors='''pt''' ).pixel_values with torch.no_grad(): __SCREAMING_SNAKE_CASE : Optional[Any] = model(snake_case ) if model_name == "upernet-convnext-tiny": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": __SCREAMING_SNAKE_CASE : int = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": __SCREAMING_SNAKE_CASE : Dict = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print('''Logits:''' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , snake_case , atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(snake_case ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(snake_case ) if push_to_hub: print(F'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(F'''openmmlab/{model_name}''' ) processor.push_to_hub(F'''openmmlab/{model_name}''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-convnext-tiny""", type=str, choices=[f'''upernet-convnext-{size}''' for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]], help="""Name of the ConvNext UperNet 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 or not to push the converted model to the 🤗 hub.""" ) lowercase_ = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
74
import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" super().tearDown() gc.collect() def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( '''stabilityai/stable-diffusion-2''' , revision='''bf16''' , dtype=jnp.bfloataa , ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''A painting of a squirrel eating a burger''' __SCREAMING_SNAKE_CASE : int = jax.device_count() __SCREAMING_SNAKE_CASE : Tuple = num_samples * [prompt] __SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.prepare_inputs(_A ) __SCREAMING_SNAKE_CASE : Tuple = replicate(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = shard(_A ) __SCREAMING_SNAKE_CASE : Dict = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = jax.random.split(_A , jax.device_count() ) __SCREAMING_SNAKE_CASE : str = sd_pipe(_A , _A , _A , num_inference_steps=25 , jit=_A )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) __SCREAMING_SNAKE_CASE : List[str] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = images[0, 253:256, 253:256, -1] __SCREAMING_SNAKE_CASE : Dict = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __SCREAMING_SNAKE_CASE : Tuple = jnp.array([0.42_38, 0.44_14, 0.43_95, 0.44_53, 0.46_29, 0.45_90, 0.45_31, 0.4_55_08, 0.45_12] ) print(F'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = '''stabilityai/stable-diffusion-2''' __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = FlaxDPMSolverMultistepScheduler.from_pretrained(_A , subfolder='''scheduler''' ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = FlaxStableDiffusionPipeline.from_pretrained( _A , scheduler=_A , revision='''bf16''' , dtype=jnp.bfloataa , ) __SCREAMING_SNAKE_CASE : List[str] = scheduler_params __SCREAMING_SNAKE_CASE : Tuple = '''A painting of a squirrel eating a burger''' __SCREAMING_SNAKE_CASE : List[Any] = jax.device_count() __SCREAMING_SNAKE_CASE : Tuple = num_samples * [prompt] __SCREAMING_SNAKE_CASE : Any = sd_pipe.prepare_inputs(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = replicate(_A ) __SCREAMING_SNAKE_CASE : List[str] = shard(_A ) __SCREAMING_SNAKE_CASE : int = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = jax.random.split(_A , jax.device_count() ) __SCREAMING_SNAKE_CASE : List[Any] = sd_pipe(_A , _A , _A , num_inference_steps=25 , jit=_A )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) __SCREAMING_SNAKE_CASE : Tuple = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __SCREAMING_SNAKE_CASE : Dict = images[0, 253:256, 253:256, -1] __SCREAMING_SNAKE_CASE : Optional[int] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.array([0.43_36, 0.4_29_69, 0.44_53, 0.41_99, 0.42_97, 0.45_31, 0.44_34, 0.44_34, 0.42_97] ) print(F'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
74
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): lowercase_ = """pt""" elif is_tf_available(): lowercase_ = """tf""" else: lowercase_ = """jax""" class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ByTaTokenizer lowerCAmelCase_ = False def UpperCAmelCase__ ( self : int ): """simple docstring""" super().setUp() __SCREAMING_SNAKE_CASE : Any = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" return ByTaTokenizer.from_pretrained('''google/byt5-small''' ) def UpperCAmelCase__ ( self : Tuple , **_A : Any ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase__ ( self : str , _A : Optional[Any] , _A : Union[str, Any]=False , _A : Optional[int]=20 , _A : Optional[Any]=5 ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [] for i in range(len(_A ) ): try: __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=_A ) except UnicodeDecodeError: pass toks.append((i, tok) ) __SCREAMING_SNAKE_CASE : Dict = list(filter(lambda _A : re.match(r'''^[ a-zA-Z]+$''' , t[1] ) , _A ) ) __SCREAMING_SNAKE_CASE : Optional[int] = list(filter(lambda _A : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_A ) , _A ) ) if max_length is not None and len(_A ) > max_length: __SCREAMING_SNAKE_CASE : str = toks[:max_length] if min_length is not None and len(_A ) < min_length and len(_A ) > 0: while len(_A ) < min_length: __SCREAMING_SNAKE_CASE : List[Any] = toks + toks # toks_str = [t[1] for t in toks] __SCREAMING_SNAKE_CASE : Union[str, Any] = [t[0] for t in toks] # Ensure consistency __SCREAMING_SNAKE_CASE : int = tokenizer.decode(_A , clean_up_tokenization_spaces=_A ) if " " not in output_txt and len(_A ) > 1: __SCREAMING_SNAKE_CASE : str = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_A ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_A ) ) if with_prefix_space: __SCREAMING_SNAKE_CASE : str = ''' ''' + output_txt __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A , add_special_tokens=_A ) return output_txt, output_ids def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.ta_base_tokenizer __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(['''hi</s>''', '''I went to the gym</s>''', '''</s>'''] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(['''hi''', '''I went to the gym''', ''''''] ) self.assertListEqual(batch_with_eos_added['''input_ids'''] , batch_without_eos_added['''input_ids'''] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.ta_base_tokenizer __SCREAMING_SNAKE_CASE : Tuple = '''Unicode €.''' __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['''input_ids'''] , _A ) # decoding __SCREAMING_SNAKE_CASE : Any = tokenizer.decode(_A ) self.assertEqual(_A , '''Unicode €.</s>''' ) __SCREAMING_SNAKE_CASE : Dict = tokenizer('''e è é ê ë''' ) __SCREAMING_SNAKE_CASE : str = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['''input_ids'''] , _A ) # decoding __SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(_A ) self.assertEqual(_A , '''e è é ê ë</s>''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''e è é ê ë</s>''' ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.ta_base_tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off __SCREAMING_SNAKE_CASE : Optional[Any] = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = tokenizer(_A , padding=_A , return_tensors=_A ) self.assertIsInstance(_A , _A ) if FRAMEWORK != "jax": __SCREAMING_SNAKE_CASE : int = list(batch.input_ids.numpy()[0] ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = list(batch.input_ids.tolist()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.ta_base_tokenizer __SCREAMING_SNAKE_CASE : Any = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] __SCREAMING_SNAKE_CASE : List[Any] = tokenizer(_A , padding=_A , return_tensors=_A ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , _A ) self.assertIn('''attention_mask''' , _A ) self.assertNotIn('''decoder_input_ids''' , _A ) self.assertNotIn('''decoder_attention_mask''' , _A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.ta_base_tokenizer __SCREAMING_SNAKE_CASE : List[str] = [ '''Summary of the text.''', '''Another summary.''', ] __SCREAMING_SNAKE_CASE : List[str] = tokenizer( text_target=_A , max_length=32 , padding='''max_length''' , truncation=_A , return_tensors=_A ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.ta_base_tokenizer __SCREAMING_SNAKE_CASE : int = ['''A long paragraph for summarization. </s>'''] __SCREAMING_SNAKE_CASE : Any = ['''Summary of the text. </s>'''] # fmt: off __SCREAMING_SNAKE_CASE : Any = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] __SCREAMING_SNAKE_CASE : Any = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on __SCREAMING_SNAKE_CASE : str = tokenizer(_A , text_target=_A ) self.assertEqual(_A , batch['''input_ids'''][0] ) self.assertEqual(_A , batch['''labels'''][0] ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test __SCREAMING_SNAKE_CASE : int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : Optional[int] = ''' He is very happy, UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A , add_special_tokens=_A ) tokenizer.save_pretrained(_A ) __SCREAMING_SNAKE_CASE : int = tokenizer.__class__.from_pretrained(_A ) __SCREAMING_SNAKE_CASE : int = after_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) shutil.rmtree(_A ) __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : List[Any] = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) __SCREAMING_SNAKE_CASE : int = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) __SCREAMING_SNAKE_CASE : int = tokenizer.encode(_A , add_special_tokens=_A ) tokenizer.save_pretrained(_A ) __SCREAMING_SNAKE_CASE : str = tokenizer.__class__.from_pretrained(_A ) __SCREAMING_SNAKE_CASE : List[str] = after_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.__class__.from_pretrained(_A , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_A ) with open(os.path.join(_A , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: __SCREAMING_SNAKE_CASE : List[str] = json.load(_A ) with open(os.path.join(_A , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: __SCREAMING_SNAKE_CASE : Any = json.load(_A ) __SCREAMING_SNAKE_CASE : List[Any] = [F'''<extra_id_{i}>''' for i in range(125 )] __SCREAMING_SNAKE_CASE : Tuple = added_tokens_extra_ids + [ '''an_additional_special_token''' ] __SCREAMING_SNAKE_CASE : str = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(_A , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(_A , _A ) with open(os.path.join(_A , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(_A , _A ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __SCREAMING_SNAKE_CASE : Tuple = tokenizer_class.from_pretrained( _A , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __SCREAMING_SNAKE_CASE : Tuple = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=_A )] __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_class.from_pretrained( _A , additional_special_tokens=_A , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_class.from_pretrained(_A ) self.assertTrue(tokenizer.decode([255] ) == '''''' ) def UpperCAmelCase__ ( self : int ): """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ): """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ): """simple docstring""" pass def UpperCAmelCase__ ( self : str ): """simple docstring""" pass def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizers(fast=_A , do_lower_case=_A ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): __SCREAMING_SNAKE_CASE : Optional[int] = ['''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''x''', '''t''', '''</s>'''] __SCREAMING_SNAKE_CASE : List[Any] = tokenizer.convert_tokens_to_string(_A ) self.assertIsInstance(_A , _A ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): __SCREAMING_SNAKE_CASE : Dict = [ '''bos_token''', '''eos_token''', '''unk_token''', '''sep_token''', '''pad_token''', '''cls_token''', '''mask_token''', ] __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.convert_ids_to_tokens( _A , skip_special_tokens=_A ) for attr in attributes_list: setattr(_A , attr + '''_id''' , _A ) self.assertEqual(getattr(_A , _A ) , _A ) self.assertEqual(getattr(_A , attr + '''_id''' ) , _A ) setattr(_A , attr + '''_id''' , _A ) self.assertEqual(getattr(_A , _A ) , _A ) self.assertEqual(getattr(_A , attr + '''_id''' ) , _A ) setattr(_A , '''additional_special_tokens_ids''' , [] ) self.assertListEqual(getattr(_A , '''additional_special_tokens''' ) , [] ) self.assertListEqual(getattr(_A , '''additional_special_tokens_ids''' ) , [] ) setattr(_A , '''additional_special_tokens_ids''' , [token_id_to_test_setters] ) self.assertListEqual(getattr(_A , '''additional_special_tokens''' ) , [token_to_test_setters] ) self.assertListEqual(getattr(_A , '''additional_special_tokens_ids''' ) , [token_id_to_test_setters] )
74
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) lowercase_ = { """configuration_layoutlmv2""": ["""LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMv2Config"""], """processing_layoutlmv2""": ["""LayoutLMv2Processor"""], """tokenization_layoutlmv2""": ["""LayoutLMv2Tokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""LayoutLMv2TokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""LayoutLMv2FeatureExtractor"""] lowercase_ = ["""LayoutLMv2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST""", """LayoutLMv2ForQuestionAnswering""", """LayoutLMv2ForSequenceClassification""", """LayoutLMv2ForTokenClassification""", """LayoutLMv2Layer""", """LayoutLMv2Model""", """LayoutLMv2PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
74
1
from ..utils import DummyObject, requires_backends class __UpperCamelCase ( metaclass=lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Any , *_A : List[Any] , **_A : Optional[int] ): """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Optional[Any] , *_A : List[str] , **_A : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : List[str] , *_A : Any , **_A : Optional[int] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __UpperCamelCase ( metaclass=lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[Any] , *_A : str , **_A : Union[str, Any] ): """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Union[str, Any] , *_A : List[Any] , **_A : Optional[int] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Union[str, Any] , *_A : Dict , **_A : int ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __UpperCamelCase ( metaclass=lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[str] , *_A : Union[str, Any] , **_A : Optional[int] ): """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : str , *_A : Tuple , **_A : Any ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Dict , *_A : int , **_A : Optional[Any] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __UpperCamelCase ( metaclass=lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Optional[Any] , *_A : int , **_A : List[Any] ): """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : List[str] , *_A : Union[str, Any] , **_A : Optional[int] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Union[str, Any] , *_A : Any , **_A : List[Any] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __UpperCamelCase ( metaclass=lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *_A : Any , **_A : Any ): """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Optional[int] , *_A : List[Any] , **_A : Any ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Optional[int] , *_A : str , **_A : str ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class __UpperCamelCase ( metaclass=lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[str] , *_A : Union[str, Any] , **_A : int ): """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Tuple , *_A : int , **_A : Optional[int] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def UpperCAmelCase__ ( cls : Any , *_A : int , **_A : List[Any] ): """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] )
74
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MobileBertTokenizer lowerCAmelCase_ = MobileBertTokenizerFast lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = filter_non_english lowerCAmelCase_ = '''google/mobilebert-uncased''' def UpperCAmelCase__ ( self : Dict ): """simple docstring""" super().setUp() __SCREAMING_SNAKE_CASE : List[str] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : int = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def UpperCAmelCase__ ( self : Tuple , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : List[str] = '''unwanted, running''' return input_text, output_text def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase__ ( self : int ): """simple docstring""" if not self.test_rust_tokenizer: return __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : str = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Any = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : str = tokenizer.encode(_A ) __SCREAMING_SNAKE_CASE : Any = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) # With lower casing __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer(do_lower_case=_A ) __SCREAMING_SNAKE_CASE : List[str] = self.get_rust_tokenizer(do_lower_case=_A ) __SCREAMING_SNAKE_CASE : List[str] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : int = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Any = tokenizer.encode(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BasicTokenizer(do_lower_case=_A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] __SCREAMING_SNAKE_CASE : Dict = {} for i, token in enumerate(_A ): __SCREAMING_SNAKE_CASE : List[str] = i __SCREAMING_SNAKE_CASE : str = WordpieceTokenizer(vocab=_A , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def UpperCAmelCase__ ( self : str ): """simple docstring""" self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(_A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(_A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode('''sequence builders''' , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Any = tokenizer.build_inputs_with_special_tokens(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : str = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_r.encode_plus( _A , return_attention_mask=_A , return_token_type_ids=_A , return_offsets_mapping=_A , add_special_tokens=_A , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_r.do_lower_case if hasattr(_A , '''do_lower_case''' ) else False __SCREAMING_SNAKE_CASE : Optional[Any] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = ['''的''', '''人''', '''有'''] __SCREAMING_SNAKE_CASE : int = ''''''.join(_A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : int = self.tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : int = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer_p.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer_r.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_r.convert_ids_to_tokens(_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = False __SCREAMING_SNAKE_CASE : Any = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer_class.from_pretrained(_A , **_A ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : Dict = tokenizer_r.convert_ids_to_tokens(_A ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE : List[Any] = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(_A ) ] self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A )
74
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , _A : int , _A : Any=7 , _A : List[str]=3 , _A : Optional[Any]=18 , _A : List[str]=30 , _A : Optional[Any]=400 , _A : Any=True , _A : List[str]=None , _A : Union[str, Any]=True , _A : Optional[int]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else {'''shortest_edge''': 20} __SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} __SCREAMING_SNAKE_CASE : int = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : List[str] = image_size __SCREAMING_SNAKE_CASE : int = min_resolution __SCREAMING_SNAKE_CASE : Optional[int] = max_resolution __SCREAMING_SNAKE_CASE : List[Any] = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : str = do_center_crop __SCREAMING_SNAKE_CASE : Any = crop_size def UpperCAmelCase__ ( self : Dict ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MobileNetVaImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = MobileNetVaImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , '''do_resize''' ) ) self.assertTrue(hasattr(_A , '''size''' ) ) self.assertTrue(hasattr(_A , '''do_center_crop''' ) ) self.assertTrue(hasattr(_A , '''crop_size''' ) ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) __SCREAMING_SNAKE_CASE : Tuple = 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 : int ): """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Any = 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 __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Any = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Optional[Any] = 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 __SCREAMING_SNAKE_CASE : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Dict = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
74
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor lowercase_ = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : Tuple , *_A : Optional[int] , **_A : Tuple ): """simple docstring""" warnings.warn( '''The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use MobileViTImageProcessor instead.''' , _A , ) super().__init__(*_A , **_A )
74
1
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[int] , _A : Union[str, Any] , _A : Union[str, Any]=7 , _A : Any=3 , _A : Union[str, Any]=18 , _A : List[Any]=30 , _A : Tuple=400 , _A : Union[str, Any]=True , _A : List[Any]=None , _A : List[str]=True , ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = size if size is not None else {'''height''': 18, '''width''': 18} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : str = image_size __SCREAMING_SNAKE_CASE : Tuple = min_resolution __SCREAMING_SNAKE_CASE : Tuple = max_resolution __SCREAMING_SNAKE_CASE : Optional[Any] = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : Any = do_normalize def UpperCAmelCase__ ( self : str ): """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.88_66_44_36_34_03_32_03, 0.66_18_82_93_69_54_49_83, 0.38_91_74_64_01_78_68_04], [-0.60_42_55_91_46_88_11_04, -0.0_22_95_00_88_60_52_84_69, 0.54_23_79_73_69_00_32_96], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ImageGPTImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = ImageGPTImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , '''clusters''' ) ) self.assertTrue(hasattr(_A , '''do_resize''' ) ) self.assertTrue(hasattr(_A , '''size''' ) ) self.assertTrue(hasattr(_A , '''do_normalize''' ) ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) __SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(_A , obj[key] ) ) else: self.assertEqual(obj[key] , _A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : List[str] = os.path.join(_A , '''image_processor.json''' ) image_processor_first.to_json_file(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class.from_json_file(_A ).to_dict() __SCREAMING_SNAKE_CASE : List[Any] = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_A , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(_A ) __SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class.from_pretrained(_A ).to_dict() __SCREAMING_SNAKE_CASE : Tuple = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_A , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _A ) @unittest.skip('''ImageGPT requires clusters at initialization''' ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" pass def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = load_dataset('''hf-internal-testing/fixtures_image_utils''' , split='''test''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(dataset[4]['''file'''] ) __SCREAMING_SNAKE_CASE : str = Image.open(dataset[5]['''file'''] ) __SCREAMING_SNAKE_CASE : List[Any] = [imagea, imagea] return images @require_vision @require_torch class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = ImageGPTImageProcessor.from_pretrained('''openai/imagegpt-small''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_images() # test non-batched __SCREAMING_SNAKE_CASE : Tuple = image_processing(images[0] , return_tensors='''pt''' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1024) ) __SCREAMING_SNAKE_CASE : Optional[int] = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , _A ) # test batched __SCREAMING_SNAKE_CASE : str = image_processing(_A , return_tensors='''pt''' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1024) ) __SCREAMING_SNAKE_CASE : Optional[int] = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , _A )
74
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast lowercase_ = datasets.utils.logging.get_logger(__name__) @dataclass class __UpperCamelCase ( datasets.BuilderConfig ): """simple docstring""" lowerCAmelCase_ = 1_00_00 lowerCAmelCase_ = None lowerCAmelCase_ = None class __UpperCamelCase ( datasets.ArrowBasedBuilder ): """simple docstring""" lowerCAmelCase_ = ParquetConfig def UpperCAmelCase__ ( self : Any ): """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def UpperCAmelCase__ ( self : Any , _A : Optional[Any] ): """simple docstring""" 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}''' ) __SCREAMING_SNAKE_CASE : List[str] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_A , (str, list, tuple) ): __SCREAMING_SNAKE_CASE : Tuple = data_files if isinstance(_A , _A ): __SCREAMING_SNAKE_CASE : Optional[int] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __SCREAMING_SNAKE_CASE : List[Any] = [dl_manager.iter_files(_A ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] __SCREAMING_SNAKE_CASE : int = [] for split_name, files in data_files.items(): if isinstance(_A , _A ): __SCREAMING_SNAKE_CASE : Any = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __SCREAMING_SNAKE_CASE : Optional[int] = [dl_manager.iter_files(_A ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(_A ): with open(_A , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : Dict = datasets.Features.from_arrow_schema(pq.read_schema(_A ) ) break splits.append(datasets.SplitGenerator(name=_A , gen_kwargs={'''files''': files} ) ) return splits def UpperCAmelCase__ ( self : str , _A : pa.Table ): """simple docstring""" if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example __SCREAMING_SNAKE_CASE : str = table_cast(_A , self.info.features.arrow_schema ) return pa_table def UpperCAmelCase__ ( self : Tuple , _A : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F'''Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'''' ) for file_idx, file in enumerate(itertools.chain.from_iterable(_A ) ): with open(_A , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : str = pq.ParquetFile(_A ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): __SCREAMING_SNAKE_CASE : Optional[Any] = pa.Table.from_batches([record_batch] ) # 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 F'''{file_idx}_{batch_idx}''', self._cast_table(_A ) except ValueError as e: logger.error(F'''Failed to read file \'{file}\' with error {type(_A )}: {e}''' ) raise
74
1
from __future__ import annotations lowercase_ = tuple[int, int, int] lowercase_ = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase lowercase_ = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- lowercase_ = """EGZWVONAHDCLFQMSIPJBYUKXTR""" lowercase_ = """FOBHMDKEXQNRAULPGSJVTYICZW""" lowercase_ = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- lowercase_ = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- lowercase_ = """RMDJXFUWGISLHVTCQNKYPBEZOA""" lowercase_ = """SGLCPQWZHKXAREONTFBVIYJUDM""" lowercase_ = """HVSICLTYKQUBXDWAJZOMFGPREN""" lowercase_ = """RZWQHFMVDBKICJLNTUXAGYPSOE""" lowercase_ = """LFKIJODBEGAMQPXVUHYSTCZRWN""" lowercase_ = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" # Checks if there are 3 unique rotors if (unique_rotsel := len(set(snake_case ) )) < 3: __SCREAMING_SNAKE_CASE : Dict = F'''Please use 3 unique rotors (not {unique_rotsel})''' raise Exception(snake_case ) # Checks if rotor positions are valid __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = rotpos if not 0 < rotorposa <= len(snake_case ): __SCREAMING_SNAKE_CASE : Tuple = F'''First rotor position is not within range of 1..26 ({rotorposa}''' raise ValueError(snake_case ) if not 0 < rotorposa <= len(snake_case ): __SCREAMING_SNAKE_CASE : Optional[int] = F'''Second rotor position is not within range of 1..26 ({rotorposa})''' raise ValueError(snake_case ) if not 0 < rotorposa <= len(snake_case ): __SCREAMING_SNAKE_CASE : Optional[Any] = F'''Third rotor position is not within range of 1..26 ({rotorposa})''' raise ValueError(snake_case ) # Validates string and returns dict __SCREAMING_SNAKE_CASE : int = _plugboard(snake_case ) return rotpos, rotsel, pbdict def a__ ( snake_case ): """simple docstring""" # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(snake_case , snake_case ): __SCREAMING_SNAKE_CASE : str = F'''Plugboard setting isn\'t type string ({type(snake_case )})''' raise TypeError(snake_case ) elif len(snake_case ) % 2 != 0: __SCREAMING_SNAKE_CASE : int = F'''Odd number of symbols ({len(snake_case )})''' raise Exception(snake_case ) elif pbstring == "": return {} pbstring.replace(''' ''' , '''''' ) # Checks if all characters are unique __SCREAMING_SNAKE_CASE : Optional[Any] = set() for i in pbstring: if i not in abc: __SCREAMING_SNAKE_CASE : Tuple = F'''\'{i}\' not in list of symbols''' raise Exception(snake_case ) elif i in tmppbl: __SCREAMING_SNAKE_CASE : Optional[int] = F'''Duplicate symbol ({i})''' raise Exception(snake_case ) else: tmppbl.add(snake_case ) del tmppbl # Created the dictionary __SCREAMING_SNAKE_CASE : List[str] = {} for j in range(0 , len(snake_case ) - 1 , 2 ): __SCREAMING_SNAKE_CASE : Optional[Any] = pbstring[j + 1] __SCREAMING_SNAKE_CASE : List[Any] = pbstring[j] return pb def a__ ( snake_case , snake_case , snake_case = (rotora, rotora, rotora) , snake_case = "" , ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = text.upper() __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = _validator( snake_case , snake_case , plugb.upper() ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = rotor_position __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : str = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 __SCREAMING_SNAKE_CASE : List[Any] = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: __SCREAMING_SNAKE_CASE : List[str] = plugboard[symbol] # rotor ra -------------------------- __SCREAMING_SNAKE_CASE : Union[str, Any] = abc.index(snake_case ) + rotorposa __SCREAMING_SNAKE_CASE : Dict = rotora[index % len(snake_case )] # rotor rb -------------------------- __SCREAMING_SNAKE_CASE : List[Any] = abc.index(snake_case ) + rotorposa __SCREAMING_SNAKE_CASE : int = rotora[index % len(snake_case )] # rotor rc -------------------------- __SCREAMING_SNAKE_CASE : Union[str, Any] = abc.index(snake_case ) + rotorposa __SCREAMING_SNAKE_CASE : Union[str, Any] = rotora[index % len(snake_case )] # reflector -------------------------- # this is the reason you don't need another machine to decipher __SCREAMING_SNAKE_CASE : int = reflector[symbol] # 2nd rotors __SCREAMING_SNAKE_CASE : Optional[int] = abc[rotora.index(snake_case ) - rotorposa] __SCREAMING_SNAKE_CASE : Union[str, Any] = abc[rotora.index(snake_case ) - rotorposa] __SCREAMING_SNAKE_CASE : Any = abc[rotora.index(snake_case ) - rotorposa] # 2nd plugboard if symbol in plugboard: __SCREAMING_SNAKE_CASE : int = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(snake_case ): __SCREAMING_SNAKE_CASE : str = 0 rotorposa += 1 if rotorposa >= len(snake_case ): __SCREAMING_SNAKE_CASE : Tuple = 0 rotorposa += 1 if rotorposa >= len(snake_case ): __SCREAMING_SNAKE_CASE : Optional[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(snake_case ) return "".join(snake_case ) if __name__ == "__main__": lowercase_ = """This is my Python script that emulates the Enigma machine from WWII.""" lowercase_ = (1, 1, 1) lowercase_ = """pictures""" lowercase_ = (rotora, rotora, rotora) lowercase_ = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
74
from math import isclose, sqrt def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = point_y / 4 / point_x __SCREAMING_SNAKE_CASE : int = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __SCREAMING_SNAKE_CASE : Tuple = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __SCREAMING_SNAKE_CASE : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __SCREAMING_SNAKE_CASE : int = outgoing_gradient**2 + 4 __SCREAMING_SNAKE_CASE : List[str] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __SCREAMING_SNAKE_CASE : Optional[Any] = (point_y - outgoing_gradient * point_x) ** 2 - 100 __SCREAMING_SNAKE_CASE : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __SCREAMING_SNAKE_CASE : int = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __SCREAMING_SNAKE_CASE : Dict = x_minus if isclose(snake_case , snake_case ) else x_plus __SCREAMING_SNAKE_CASE : Dict = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def a__ ( snake_case = 1.4 , snake_case = -9.6 ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : float = first_x_coord __SCREAMING_SNAKE_CASE : float = first_y_coord __SCREAMING_SNAKE_CASE : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = next_point(snake_case , snake_case , snake_case ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
74
1
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 __UpperCamelCase ( folder_based_builder.FolderBasedBuilderConfig ): """simple docstring""" lowerCAmelCase_ = None lowerCAmelCase_ = None class __UpperCamelCase ( folder_based_builder.FolderBasedBuilder ): """simple docstring""" lowerCAmelCase_ = datasets.Audio() lowerCAmelCase_ = '''audio''' lowerCAmelCase_ = AudioFolderConfig lowerCAmelCase_ = 42 # definition at the bottom of the script lowerCAmelCase_ = 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
74
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , _A : int , _A : Any=7 , _A : List[str]=3 , _A : Optional[Any]=18 , _A : List[str]=30 , _A : Optional[Any]=400 , _A : Any=True , _A : List[str]=None , _A : Union[str, Any]=True , _A : Optional[int]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else {'''shortest_edge''': 20} __SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} __SCREAMING_SNAKE_CASE : int = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : List[str] = image_size __SCREAMING_SNAKE_CASE : int = min_resolution __SCREAMING_SNAKE_CASE : Optional[int] = max_resolution __SCREAMING_SNAKE_CASE : List[Any] = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : str = do_center_crop __SCREAMING_SNAKE_CASE : Any = crop_size def UpperCAmelCase__ ( self : Dict ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MobileNetVaImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = MobileNetVaImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , '''do_resize''' ) ) self.assertTrue(hasattr(_A , '''size''' ) ) self.assertTrue(hasattr(_A , '''do_center_crop''' ) ) self.assertTrue(hasattr(_A , '''crop_size''' ) ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) __SCREAMING_SNAKE_CASE : Tuple = 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 : int ): """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Any = 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 __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Any = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Optional[Any] = 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 __SCREAMING_SNAKE_CASE : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Dict = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
74
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def a__ ( snake_case ): """simple docstring""" return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = create_tensor(snake_case ) __SCREAMING_SNAKE_CASE : Optional[Any] = gather(snake_case ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = [state.process_index] __SCREAMING_SNAKE_CASE : Optional[int] = gather_object(snake_case ) assert len(snake_case ) == state.num_processes, F'''{gathered_obj}, {len(snake_case )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), F'''{gathered_obj} != {list(range(state.num_processes ) )}''' def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = create_tensor(snake_case ) __SCREAMING_SNAKE_CASE : Optional[Any] = broadcast(snake_case ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def a__ ( snake_case ): """simple docstring""" # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: __SCREAMING_SNAKE_CASE : Optional[Any] = torch.arange(state.num_processes + 1 ).to(state.device ) else: __SCREAMING_SNAKE_CASE : List[str] = torch.arange(state.num_processes ).to(state.device ) __SCREAMING_SNAKE_CASE : List[Any] = pad_across_processes(snake_case ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def a__ ( snake_case ): """simple docstring""" # For now runs on only two processes if state.num_processes != 2: return __SCREAMING_SNAKE_CASE : Any = create_tensor(snake_case ) __SCREAMING_SNAKE_CASE : str = reduce(snake_case , '''sum''' ) __SCREAMING_SNAKE_CASE : int = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(snake_case , snake_case ), F'''{reduced_tensor} != {truth_tensor}''' def a__ ( snake_case ): """simple docstring""" # For now runs on only two processes if state.num_processes != 2: return __SCREAMING_SNAKE_CASE : Dict = create_tensor(snake_case ) __SCREAMING_SNAKE_CASE : Any = reduce(snake_case , '''mean''' ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(snake_case , snake_case ), F'''{reduced_tensor} != {truth_tensor}''' def a__ ( snake_case ): """simple docstring""" # For xla_spawn (TPUs) main() def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = PartialState() state.print(F'''State: {state}''' ) state.print('''testing gather''' ) test_gather(snake_case ) state.print('''testing gather_object''' ) test_gather_object(snake_case ) state.print('''testing broadcast''' ) test_broadcast(snake_case ) state.print('''testing pad_across_processes''' ) test_pad_across_processes(snake_case ) state.print('''testing reduce_sum''' ) test_reduce_sum(snake_case ) state.print('''testing reduce_mean''' ) test_reduce_mean(snake_case ) if __name__ == "__main__": main()
74
def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = [0 for i in range(len(snake_case ) )] # initialize interval's left pointer and right pointer __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = 0, 0 for i in range(1 , len(snake_case ) ): # case when current index is inside the interval if i <= right_pointer: __SCREAMING_SNAKE_CASE : List[Any] = min(right_pointer - i + 1 , z_result[i - left_pointer] ) __SCREAMING_SNAKE_CASE : Dict = min_edge while go_next(snake_case , snake_case , snake_case ): 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: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = i, i + z_result[i] - 1 return z_result def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" return i + z_result[i] < len(snake_case ) and s[z_result[i]] == s[i + z_result[i]] def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string __SCREAMING_SNAKE_CASE : str = 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(snake_case ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
74
1
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = ['''vqvae'''] def __init__( self : Dict , _A : AutoencoderKL , _A : UNetaDConditionModel , _A : Mel , _A : Union[DDIMScheduler, DDPMScheduler] , ): """simple docstring""" super().__init__() self.register_modules(unet=_A , scheduler=_A , mel=_A , vqvae=_A ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return 50 if isinstance(self.scheduler , _A ) else 1000 @torch.no_grad() def __call__( self : Dict , _A : int = 1 , _A : str = None , _A : np.ndarray = None , _A : int = 0 , _A : int = 0 , _A : int = None , _A : torch.Generator = None , _A : float = 0 , _A : float = 0 , _A : torch.Generator = None , _A : float = 0 , _A : torch.Tensor = None , _A : torch.Tensor = None , _A : Union[str, Any]=True , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = steps or self.get_default_steps() self.scheduler.set_timesteps(_A ) __SCREAMING_SNAKE_CASE : int = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: __SCREAMING_SNAKE_CASE : List[Any] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: __SCREAMING_SNAKE_CASE : int = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=_A , device=self.device , ) __SCREAMING_SNAKE_CASE : Any = noise __SCREAMING_SNAKE_CASE : List[str] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(_A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = self.mel.audio_slice_to_image(_A ) __SCREAMING_SNAKE_CASE : List[Any] = np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) __SCREAMING_SNAKE_CASE : List[str] = (input_image / 255) * 2 - 1 __SCREAMING_SNAKE_CASE : str = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = self.vqvae.encode(torch.unsqueeze(_A , 0 ) ).latent_dist.sample( generator=_A )[0] __SCREAMING_SNAKE_CASE : Any = self.vqvae.config.scaling_factor * input_images if start_step > 0: __SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler.add_noise(_A , _A , self.scheduler.timesteps[start_step - 1] ) __SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) __SCREAMING_SNAKE_CASE : Tuple = int(mask_start_secs * pixels_per_second ) __SCREAMING_SNAKE_CASE : List[Any] = int(mask_end_secs * pixels_per_second ) __SCREAMING_SNAKE_CASE : str = self.scheduler.add_noise(_A , _A , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , _A ): __SCREAMING_SNAKE_CASE : List[str] = self.unet(_A , _A , _A )['''sample'''] else: __SCREAMING_SNAKE_CASE : List[Any] = self.unet(_A , _A )['''sample'''] if isinstance(self.scheduler , _A ): __SCREAMING_SNAKE_CASE : int = self.scheduler.step( model_output=_A , timestep=_A , sample=_A , eta=_A , generator=_A , )['''prev_sample'''] else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( model_output=_A , timestep=_A , sample=_A , generator=_A , )['''prev_sample'''] if mask is not None: if mask_start > 0: __SCREAMING_SNAKE_CASE : Optional[int] = mask[:, step, :, :mask_start] if mask_end > 0: __SCREAMING_SNAKE_CASE : Union[str, Any] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance __SCREAMING_SNAKE_CASE : Optional[int] = 1 / self.vqvae.config.scaling_factor * images __SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(_A )['''sample'''] __SCREAMING_SNAKE_CASE : Optional[int] = (images / 2 + 0.5).clamp(0 , 1 ) __SCREAMING_SNAKE_CASE : int = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() __SCREAMING_SNAKE_CASE : Optional[Any] = (images * 255).round().astype('''uint8''' ) __SCREAMING_SNAKE_CASE : Dict = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(_A , mode='''RGB''' ).convert('''L''' ) for _ in images) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [self.mel.image_to_audio(_A ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(_A )[:, np.newaxis, :] ) , **ImagePipelineOutput(_A ) ) @torch.no_grad() def UpperCAmelCase__ ( self : List[str] , _A : List[Image.Image] , _A : int = 50 ): """simple docstring""" assert isinstance(self.scheduler , _A ) self.scheduler.set_timesteps(_A ) __SCREAMING_SNAKE_CASE : List[str] = np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) __SCREAMING_SNAKE_CASE : Optional[Any] = (sample / 255) * 2 - 1 __SCREAMING_SNAKE_CASE : List[Any] = torch.Tensor(_A ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): __SCREAMING_SNAKE_CASE : int = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps __SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.alphas_cumprod[t] __SCREAMING_SNAKE_CASE : Any = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 1 - alpha_prod_t __SCREAMING_SNAKE_CASE : Dict = self.unet(_A , _A )['''sample'''] __SCREAMING_SNAKE_CASE : str = (1 - alpha_prod_t_prev) ** 0.5 * model_output __SCREAMING_SNAKE_CASE : Dict = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) __SCREAMING_SNAKE_CASE : Tuple = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCAmelCase__ ( _A : torch.Tensor , _A : torch.Tensor , _A : float ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = acos(torch.dot(torch.flatten(_A ) , torch.flatten(_A ) ) / torch.norm(_A ) / torch.norm(_A ) ) return sin((1 - alpha) * theta ) * xa / sin(_A ) + sin(alpha * theta ) * xa / sin(_A )
74
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase_ = {"""configuration_swin""": ["""SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SwinConfig""", """SwinOnnxConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""", """SwinForImageClassification""", """SwinForMaskedImageModeling""", """SwinModel""", """SwinPreTrainedModel""", """SwinBackbone""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSwinForImageClassification""", """TFSwinForMaskedImageModeling""", """TFSwinModel""", """TFSwinPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
74
1
from math import sqrt def a__ ( snake_case = 1_000_000 ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(snake_case , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
74
import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = XCLIPTextConfig() # derive patch size from model name __SCREAMING_SNAKE_CASE : Tuple = model_name.find('''patch''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(model_name[start_idx + len('''patch''' ) : start_idx + len('''patch''' ) + 2] ) __SCREAMING_SNAKE_CASE : Tuple = XCLIPVisionConfig(patch_size=snake_case , num_frames=snake_case ) if "large" in model_name: __SCREAMING_SNAKE_CASE : Optional[Any] = 768 __SCREAMING_SNAKE_CASE : Optional[int] = 3_072 __SCREAMING_SNAKE_CASE : Optional[Any] = 12 __SCREAMING_SNAKE_CASE : Optional[Any] = 1_024 __SCREAMING_SNAKE_CASE : int = 4_096 __SCREAMING_SNAKE_CASE : Tuple = 16 __SCREAMING_SNAKE_CASE : Optional[int] = 24 __SCREAMING_SNAKE_CASE : Optional[int] = 768 __SCREAMING_SNAKE_CASE : Optional[int] = 3_072 if model_name == "xclip-large-patch14-16-frames": __SCREAMING_SNAKE_CASE : Any = 336 __SCREAMING_SNAKE_CASE : Any = XCLIPConfig.from_text_vision_configs(snake_case , snake_case ) if "large" in model_name: __SCREAMING_SNAKE_CASE : Any = 768 return config def a__ ( snake_case ): """simple docstring""" # text encoder if name == "token_embedding.weight": __SCREAMING_SNAKE_CASE : List[str] = name.replace('''token_embedding.weight''' , '''text_model.embeddings.token_embedding.weight''' ) if name == "positional_embedding": __SCREAMING_SNAKE_CASE : List[str] = name.replace('''positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "ln_1" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: __SCREAMING_SNAKE_CASE : str = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''c_proj''' , '''fc2''' ) if name.startswith('''transformer.resblocks''' ): __SCREAMING_SNAKE_CASE : Any = name.replace('''transformer.resblocks''' , '''text_model.encoder.layers''' ) if "attn.out_proj" in name and "message" not in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''attn.out_proj''' , '''self_attn.out_proj''' ) if "ln_final" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace('''ln_final''' , '''text_model.final_layer_norm''' ) # visual encoder if name == "visual.class_embedding": __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace('''visual.class_embedding''' , '''vision_model.embeddings.class_embedding''' ) if name == "visual.positional_embedding": __SCREAMING_SNAKE_CASE : Tuple = name.replace('''visual.positional_embedding''' , '''vision_model.embeddings.position_embedding.weight''' ) if name.startswith('''visual.transformer.resblocks''' ): __SCREAMING_SNAKE_CASE : List[Any] = name.replace('''visual.transformer.resblocks''' , '''vision_model.encoder.layers''' ) if "visual.conv1" in name: __SCREAMING_SNAKE_CASE : Any = name.replace('''visual.conv1''' , '''vision_model.embeddings.patch_embedding''' ) if "visual.ln_pre" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace('''visual.ln_pre''' , '''vision_model.pre_layernorm''' ) if "visual.ln_post" in name: __SCREAMING_SNAKE_CASE : Dict = name.replace('''visual.ln_post''' , '''vision_model.post_layernorm''' ) if "visual.proj" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''visual.proj''' , '''visual_projection.weight''' ) if "text_projection" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''text_projection''' , '''text_projection.weight''' ) # things on top if "prompts_visual_proj" in name: __SCREAMING_SNAKE_CASE : str = name.replace('''prompts_visual_proj''' , '''prompts_visual_projection''' ) if "prompts_visual_ln" in name: __SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''prompts_visual_ln''' , '''prompts_visual_layernorm''' ) # mit if name == "mit.positional_embedding": __SCREAMING_SNAKE_CASE : Any = name.replace('''positional''' , '''position''' ) if name.startswith('''mit.resblocks''' ): __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''mit.resblocks''' , '''mit.encoder.layers''' ) # prompts generator if name.startswith('''prompts_generator.norm''' ): __SCREAMING_SNAKE_CASE : Tuple = name.replace('''prompts_generator.norm''' , '''prompts_generator.layernorm''' ) return name def a__ ( snake_case , snake_case ): """simple docstring""" for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE : Tuple = orig_state_dict.pop(snake_case ) if "attn.in_proj" in key: __SCREAMING_SNAKE_CASE : Optional[Any] = key.split('''.''' ) if key.startswith('''visual''' ): __SCREAMING_SNAKE_CASE : List[Any] = key_split[3] __SCREAMING_SNAKE_CASE : Any = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = val[ :dim, : ] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : Tuple = val[ -dim:, : ] else: __SCREAMING_SNAKE_CASE : Optional[Any] = val[ :dim ] __SCREAMING_SNAKE_CASE : Tuple = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Tuple = val[ -dim: ] else: if "weight" in key: __SCREAMING_SNAKE_CASE : Tuple = val[ :dim, : ] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : str = val[ -dim:, : ] else: __SCREAMING_SNAKE_CASE : Dict = val[:dim] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Tuple = val[-dim:] elif key.startswith('''mit''' ): __SCREAMING_SNAKE_CASE : List[str] = key_split[2] __SCREAMING_SNAKE_CASE : Union[str, Any] = config.vision_config.mit_hidden_size if "weight" in key: __SCREAMING_SNAKE_CASE : str = val[:dim, :] __SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] __SCREAMING_SNAKE_CASE : Optional[int] = val[-dim:, :] else: __SCREAMING_SNAKE_CASE : Any = val[:dim] __SCREAMING_SNAKE_CASE : Any = val[dim : dim * 2] __SCREAMING_SNAKE_CASE : Optional[Any] = val[-dim:] else: __SCREAMING_SNAKE_CASE : Optional[Any] = key_split[2] __SCREAMING_SNAKE_CASE : Any = config.text_config.hidden_size if "weight" in key: __SCREAMING_SNAKE_CASE : Tuple = val[:dim, :] __SCREAMING_SNAKE_CASE : int = val[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: __SCREAMING_SNAKE_CASE : Tuple = val[:dim] __SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : int = val[-dim:] else: __SCREAMING_SNAKE_CASE : int = rename_key(snake_case ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: __SCREAMING_SNAKE_CASE : int = val.T __SCREAMING_SNAKE_CASE : Union[str, Any] = val return orig_state_dict def a__ ( snake_case ): """simple docstring""" if num_frames == 8: __SCREAMING_SNAKE_CASE : List[Any] = '''eating_spaghetti_8_frames.npy''' elif num_frames == 16: __SCREAMING_SNAKE_CASE : Tuple = '''eating_spaghetti.npy''' elif num_frames == 32: __SCREAMING_SNAKE_CASE : Dict = '''eating_spaghetti_32_frames.npy''' __SCREAMING_SNAKE_CASE : List[str] = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename=snake_case , repo_type='''dataset''' , ) __SCREAMING_SNAKE_CASE : int = np.load(snake_case ) return list(snake_case ) def a__ ( snake_case , snake_case=None , snake_case=False ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = { # fully supervised kinetics-400 checkpoints '''xclip-base-patch32''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth''', '''xclip-base-patch32-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth''' ), '''xclip-base-patch16''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth''', '''xclip-base-patch16-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth''' ), '''xclip-large-patch14''': '''https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb''', '''xclip-large-patch14-16-frames''': '''https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f''', # fully supervised kinetics-600 checkpoints '''xclip-base-patch16-kinetics-600''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth''' ), '''xclip-base-patch16-kinetics-600-16-frames''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth''' ), '''xclip-large-patch14-kinetics-600''': '''https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be''', # few shot '''xclip-base-patch16-hmdb-2-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth''' ), '''xclip-base-patch16-hmdb-4-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth''' ), '''xclip-base-patch16-hmdb-8-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth''' ), '''xclip-base-patch16-hmdb-16-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth''' ), '''xclip-base-patch16-ucf-2-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth''' ), '''xclip-base-patch16-ucf-4-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth''' ), '''xclip-base-patch16-ucf-8-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth''' ), '''xclip-base-patch16-ucf-16-shot''': ( '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth''' ), # zero shot '''xclip-base-patch16-zero-shot''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth''', } __SCREAMING_SNAKE_CASE : Optional[Any] = model_to_url[model_name] __SCREAMING_SNAKE_CASE : Any = 8 if "16-frames" in model_name: __SCREAMING_SNAKE_CASE : Optional[int] = 16 elif "shot" in model_name: __SCREAMING_SNAKE_CASE : Optional[Any] = 32 __SCREAMING_SNAKE_CASE : List[str] = get_xclip_config(snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Tuple = XCLIPModel(snake_case ) model.eval() if "drive" in checkpoint_url: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''pytorch_model.bin''' gdown.cached_download(snake_case , snake_case , quiet=snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(snake_case , map_location='''cpu''' )['''model'''] else: __SCREAMING_SNAKE_CASE : str = torch.hub.load_state_dict_from_url(snake_case )['''model'''] __SCREAMING_SNAKE_CASE : List[Any] = convert_state_dict(snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = XCLIPModel(snake_case ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Any = model.load_state_dict(snake_case , strict=snake_case ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() __SCREAMING_SNAKE_CASE : Any = 336 if model_name == '''xclip-large-patch14-16-frames''' else 224 __SCREAMING_SNAKE_CASE : str = VideoMAEImageProcessor(size=snake_case ) __SCREAMING_SNAKE_CASE : int = CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32''' ) __SCREAMING_SNAKE_CASE : Optional[int] = CLIPTokenizerFast.from_pretrained('''openai/clip-vit-base-patch32''' ) __SCREAMING_SNAKE_CASE : List[Any] = XCLIPProcessor(image_processor=snake_case , tokenizer=snake_case ) __SCREAMING_SNAKE_CASE : Dict = prepare_video(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = processor( text=['''playing sports''', '''eating spaghetti''', '''go shopping'''] , videos=snake_case , return_tensors='''pt''' , padding=snake_case ) print('''Shape of pixel values:''' , inputs.pixel_values.shape ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Optional[Any] = model(**snake_case ) # Verify outputs __SCREAMING_SNAKE_CASE : Dict = outputs.logits_per_video __SCREAMING_SNAKE_CASE : Tuple = logits_per_video.softmax(dim=1 ) print('''Probs:''' , snake_case ) # kinetics-400 if model_name == "xclip-base-patch32": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0.0019, 0.9951, 0.0030]] ) elif model_name == "xclip-base-patch32-16-frames": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[7.0999E-04, 9.9883E-01, 4.5580E-04]] ) elif model_name == "xclip-base-patch16": __SCREAMING_SNAKE_CASE : Dict = torch.tensor([[0.0083, 0.9681, 0.0236]] ) elif model_name == "xclip-base-patch16-16-frames": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[7.6937E-04, 9.9728E-01, 1.9473E-03]] ) elif model_name == "xclip-large-patch14": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0.0062, 0.9864, 0.0075]] ) elif model_name == "xclip-large-patch14-16-frames": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[3.3877E-04, 9.9937E-01, 2.8888E-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0.0555, 0.8914, 0.0531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[3.8554E-04, 9.9929E-01, 3.2754E-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([[0.0036, 0.9920, 0.0045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": __SCREAMING_SNAKE_CASE : str = torch.tensor([[7.1890E-06, 9.9994E-01, 5.6559E-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": __SCREAMING_SNAKE_CASE : int = torch.tensor([[1.0320E-05, 9.9993E-01, 6.2435E-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[4.1377E-06, 9.9990E-01, 9.8386E-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": __SCREAMING_SNAKE_CASE : Dict = torch.tensor([[4.1347E-05, 9.9962E-01, 3.3411E-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[8.5857E-05, 9.9928E-01, 6.3291E-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[8.5857E-05, 9.9928E-01, 6.3291E-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0.0027, 0.9904, 0.0070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[9.8219E-04, 9.9593E-01, 3.0863E-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[3.5082E-04, 9.9785E-01, 1.7966E-03]] ) else: raise ValueError(F'''Model name {model_name} not supported''' ) assert torch.allclose(snake_case , snake_case , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(snake_case ) if push_to_hub: print('''Pushing model, processor and slow tokenizer files to the hub...''' ) model.push_to_hub(snake_case , organization='''nielsr''' ) processor.push_to_hub(snake_case , organization='''nielsr''' ) slow_tokenizer.push_to_hub(snake_case , organization='''nielsr''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""xclip-base-patch32""", type=str, help="""Name of the model.""", ) 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 or not to push the converted model to the 🤗 hub.""" ) lowercase_ = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
74
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''' ) __SCREAMING_SNAKE_CASE : int = { '''input_ids''': tf.convert_to_tensor([[0, 2646, 1_0269, 83, 9_9942, 2]] , dtype=tf.intaa ), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } __SCREAMING_SNAKE_CASE : Any = model(_A )['''last_hidden_state'''] __SCREAMING_SNAKE_CASE : Dict = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , _A ) # compare the actual values for a slice. __SCREAMING_SNAKE_CASE : Dict = tf.convert_to_tensor( [ [ [0.0_68_17_62, 0.10_89_44_51, 0.06_77_25_04], [-0.06_42_36_68, 0.02_36_66_15, 0.04_32_93_44], [-0.06_05_72_95, 0.09_97_41_35, -0.00_07_05_84], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
74
from pathlib import Path import fire def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = Path(snake_case ) __SCREAMING_SNAKE_CASE : Dict = Path(snake_case ) dest_dir.mkdir(exist_ok=snake_case ) for path in src_dir.iterdir(): __SCREAMING_SNAKE_CASE : Union[str, Any] = [x.rstrip() for x in list(path.open().readlines() )][:n] __SCREAMING_SNAKE_CASE : Tuple = dest_dir.joinpath(path.name ) print(snake_case ) dest_path.open('''w''' ).write('''\n'''.join(snake_case ) ) if __name__ == "__main__": fire.Fire(minify)
74
1
from __future__ import annotations from collections.abc import MutableSequence class __UpperCamelCase : """simple docstring""" def __init__( self : int , _A : int , _A : MutableSequence[float] ): """simple docstring""" if len(_A ) != degree + 1: raise ValueError( '''The number of coefficients should be equal to the degree + 1.''' ) __SCREAMING_SNAKE_CASE : list[float] = list(_A ) __SCREAMING_SNAKE_CASE : Any = degree def __add__( self : Union[str, Any] , _A : Polynomial ): """simple docstring""" if self.degree > polynomial_a.degree: __SCREAMING_SNAKE_CASE : Any = self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree , _A ) else: __SCREAMING_SNAKE_CASE : List[str] = polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree , _A ) def __sub__( self : Any , _A : Polynomial ): """simple docstring""" return self + polynomial_a * Polynomial(0 , [-1] ) def __neg__( self : int ): """simple docstring""" return Polynomial(self.degree , [-c for c in self.coefficients] ) def __mul__( self : Tuple , _A : Polynomial ): """simple docstring""" __SCREAMING_SNAKE_CASE : list[float] = [0] * (self.degree + polynomial_a.degree + 1) for i in range(self.degree + 1 ): for j in range(polynomial_a.degree + 1 ): coefficients[i + j] += ( self.coefficients[i] * polynomial_a.coefficients[j] ) return Polynomial(self.degree + polynomial_a.degree , _A ) def UpperCAmelCase__ ( self : int , _A : int | float ): """simple docstring""" __SCREAMING_SNAKE_CASE : int | float = 0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = '''''' for i in range(self.degree , -1 , -1 ): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i] ) ) elif i == 1: polynomial += str(abs(self.coefficients[i] ) ) + "x" else: polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(_A ) return polynomial def __repr__( self : Any ): """simple docstring""" return self.__str__() def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : list[float] = [0] * self.degree for i in range(self.degree ): __SCREAMING_SNAKE_CASE : Optional[int] = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 , _A ) def UpperCAmelCase__ ( self : Union[str, Any] , _A : int | float = 0 ): """simple docstring""" __SCREAMING_SNAKE_CASE : list[float] = [0] * (self.degree + 2) __SCREAMING_SNAKE_CASE : List[Any] = constant for i in range(self.degree + 1 ): __SCREAMING_SNAKE_CASE : Dict = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 , _A ) def __eq__( self : Tuple , _A : object ): """simple docstring""" if not isinstance(_A , _A ): return False if self.degree != polynomial_a.degree: return False for i in range(self.degree + 1 ): if self.coefficients[i] != polynomial_a.coefficients[i]: return False return True def __ne__( self : Optional[Any] , _A : object ): """simple docstring""" return not self.__eq__(_A )
74
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE : Tuple = DisjunctiveConstraint(_A ) self.assertTrue(isinstance(dc.token_ids , _A ) ) with self.assertRaises(_A ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_A ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_A ): DisjunctiveConstraint(_A ) # fails here def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE : Optional[Any] = DisjunctiveConstraint(_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = dc.update(1 ) __SCREAMING_SNAKE_CASE : int = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = dc.update(2 ) __SCREAMING_SNAKE_CASE : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = dc.update(3 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = stepped is True and completed is True and reset is False self.assertTrue(_A ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE : str = DisjunctiveConstraint(_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : str = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
74
1
class __UpperCamelCase : """simple docstring""" def __init__( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = 0 __SCREAMING_SNAKE_CASE : Optional[Any] = 0 __SCREAMING_SNAKE_CASE : Optional[Any] = {} def UpperCAmelCase__ ( self : Tuple , _A : List[Any] ): """simple docstring""" if vertex not in self.adjacency: __SCREAMING_SNAKE_CASE : List[str] = {} self.num_vertices += 1 def UpperCAmelCase__ ( self : Dict , _A : Optional[Any] , _A : Optional[Any] , _A : List[str] ): """simple docstring""" self.add_vertex(_A ) self.add_vertex(_A ) if head == tail: return __SCREAMING_SNAKE_CASE : Optional[int] = weight __SCREAMING_SNAKE_CASE : Optional[int] = weight def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.get_edges() for edge in edges: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = edge edges.remove((tail, head, weight) ) for i in range(len(_A ) ): __SCREAMING_SNAKE_CASE : List[Any] = list(edges[i] ) edges.sort(key=lambda _A : e[2] ) for i in range(len(_A ) - 1 ): if edges[i][2] >= edges[i + 1][2]: __SCREAMING_SNAKE_CASE : Dict = edges[i][2] + 1 for edge in edges: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = edge __SCREAMING_SNAKE_CASE : Any = weight __SCREAMING_SNAKE_CASE : Tuple = weight def __str__( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = '''''' for tail in self.adjacency: for head in self.adjacency[tail]: __SCREAMING_SNAKE_CASE : str = self.adjacency[head][tail] string += F'''{head} -> {tail} == {weight}\n''' return string.rstrip('''\n''' ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def UpperCAmelCase__ ( self : Any ): """simple docstring""" return self.adjacency.keys() @staticmethod def UpperCAmelCase__ ( _A : List[Any]=None , _A : List[str]=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = Graph() if vertices is None: __SCREAMING_SNAKE_CASE : Optional[int] = [] if edges is None: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for vertex in vertices: g.add_vertex(_A ) for edge in edges: g.add_edge(*_A ) return g class __UpperCamelCase : """simple docstring""" def __init__( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = {} __SCREAMING_SNAKE_CASE : List[Any] = {} def __len__( self : Any ): """simple docstring""" return len(self.parent ) def UpperCAmelCase__ ( self : Dict , _A : Optional[int] ): """simple docstring""" if item in self.parent: return self.find(_A ) __SCREAMING_SNAKE_CASE : List[Any] = item __SCREAMING_SNAKE_CASE : str = 0 return item def UpperCAmelCase__ ( self : str , _A : Tuple ): """simple docstring""" if item not in self.parent: return self.make_set(_A ) if item != self.parent[item]: __SCREAMING_SNAKE_CASE : Tuple = self.find(self.parent[item] ) return self.parent[item] def UpperCAmelCase__ ( self : Any , _A : Tuple , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.find(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.find(_A ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: __SCREAMING_SNAKE_CASE : Tuple = roota return roota if self.rank[roota] < self.rank[roota]: __SCREAMING_SNAKE_CASE : str = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 __SCREAMING_SNAKE_CASE : Any = roota return roota return None @staticmethod def UpperCAmelCase__ ( _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = graph.num_vertices __SCREAMING_SNAKE_CASE : List[Any] = Graph.UnionFind() __SCREAMING_SNAKE_CASE : Union[str, Any] = [] while num_components > 1: __SCREAMING_SNAKE_CASE : str = {} for vertex in graph.get_vertices(): __SCREAMING_SNAKE_CASE : str = -1 __SCREAMING_SNAKE_CASE : List[Any] = graph.get_edges() for edge in edges: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = edge edges.remove((tail, head, weight) ) for edge in edges: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = edge __SCREAMING_SNAKE_CASE : List[Any] = union_find.find(_A ) __SCREAMING_SNAKE_CASE : Tuple = union_find.find(_A ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __SCREAMING_SNAKE_CASE : Dict = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __SCREAMING_SNAKE_CASE : int = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = cheap_edge[vertex] if union_find.find(_A ) != union_find.find(_A ): union_find.union(_A , _A ) mst_edges.append(cheap_edge[vertex] ) __SCREAMING_SNAKE_CASE : Optional[Any] = num_components - 1 __SCREAMING_SNAKE_CASE : str = Graph.build(edges=_A ) return mst
74
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) 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""") lowercase_ = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) lowercase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''The column name of the images in the files. If not set, will try to use \'image\' or \'img\'.'''} , ) lowerCAmelCase_ = field(default=lowerCAmelCase__ , metadata={'''help''': '''A folder containing the training data.'''} ) lowerCAmelCase_ = field(default=lowerCAmelCase__ , metadata={'''help''': '''A folder containing the validation data.'''} ) lowerCAmelCase_ = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) lowerCAmelCase_ = field(default=32 , metadata={'''help''': '''The size of the square patches to use for masking.'''} ) lowerCAmelCase_ = field( default=0.6 , metadata={'''help''': '''Percentage of patches to mask.'''} , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = {} if self.train_dir is not None: __SCREAMING_SNAKE_CASE : Dict = self.train_dir if self.validation_dir is not None: __SCREAMING_SNAKE_CASE : Any = self.validation_dir __SCREAMING_SNAKE_CASE : List[Any] = data_files if data_files else None @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a ''' '''checkpoint identifier on the hub. ''' '''Don\'t set if you want to train a model from scratch.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(lowerCAmelCase__ )} , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , 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''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''Where do you want to store (cache) the pretrained models/datasets downloaded from the hub'''} , ) lowerCAmelCase_ = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) lowerCAmelCase_ = field(default=lowerCAmelCase__ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''The size (resolution) of each image. If not specified, will use `image_size` of the configuration.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={ '''help''': ( '''The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.''' ) } , ) lowerCAmelCase_ = field( default=lowerCAmelCase__ , metadata={'''help''': '''Stride to use for the encoder.'''} , ) class __UpperCamelCase : """simple docstring""" def __init__( self : Tuple , _A : Optional[int]=192 , _A : List[Any]=32 , _A : Optional[int]=4 , _A : str=0.6 ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = input_size __SCREAMING_SNAKE_CASE : List[str] = mask_patch_size __SCREAMING_SNAKE_CASE : Dict = model_patch_size __SCREAMING_SNAKE_CASE : int = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('''Input size must be divisible by mask patch size''' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('''Mask patch size must be divisible by model patch size''' ) __SCREAMING_SNAKE_CASE : Any = self.input_size // self.mask_patch_size __SCREAMING_SNAKE_CASE : Optional[Any] = self.mask_patch_size // self.model_patch_size __SCREAMING_SNAKE_CASE : int = self.rand_size**2 __SCREAMING_SNAKE_CASE : Optional[int] = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = np.random.permutation(self.token_count )[: self.mask_count] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.zeros(self.token_count , dtype=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = 1 __SCREAMING_SNAKE_CASE : List[str] = mask.reshape((self.rand_size, self.rand_size) ) __SCREAMING_SNAKE_CASE : List[Any] = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.stack([example['''pixel_values'''] for example in examples] ) __SCREAMING_SNAKE_CASE : Any = torch.stack([example['''mask'''] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def a__ ( ): """simple docstring""" # 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. __SCREAMING_SNAKE_CASE : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = 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_mim''' , snake_case , snake_case ) # 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() __SCREAMING_SNAKE_CASE : Tuple = training_args.get_process_log_level() logger.setLevel(snake_case ) transformers.utils.logging.set_verbosity(snake_case ) 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. __SCREAMING_SNAKE_CASE : Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE : Optional[int] = 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. __SCREAMING_SNAKE_CASE : Tuple = 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. __SCREAMING_SNAKE_CASE : Any = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , snake_case ) and data_args.train_val_split > 0.0: __SCREAMING_SNAKE_CASE : List[str] = ds['''train'''].train_test_split(data_args.train_val_split ) __SCREAMING_SNAKE_CASE : int = split['''train'''] __SCREAMING_SNAKE_CASE : Dict = split['''test'''] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE : List[Any] = { '''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_or_path: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(model_args.config_name_or_path , **snake_case ) elif model_args.model_name_or_path: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , **snake_case ) else: __SCREAMING_SNAKE_CASE : List[Any] = CONFIG_MAPPING[model_args.model_type]() 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}''' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(snake_case , '''decoder_type''' ): __SCREAMING_SNAKE_CASE : Any = '''simmim''' # adapt config __SCREAMING_SNAKE_CASE : str = model_args.image_size if model_args.image_size is not None else config.image_size __SCREAMING_SNAKE_CASE : int = model_args.patch_size if model_args.patch_size is not None else config.patch_size __SCREAMING_SNAKE_CASE : str = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { '''image_size''': model_args.image_size, '''patch_size''': model_args.patch_size, '''encoder_stride''': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **snake_case ) elif model_args.model_name_or_path: __SCREAMING_SNAKE_CASE : List[Any] = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **snake_case ) else: __SCREAMING_SNAKE_CASE : List[Any] = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } __SCREAMING_SNAKE_CASE : str = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: __SCREAMING_SNAKE_CASE : int = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case , 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''' ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedImageModeling.from_config(snake_case ) if training_args.do_train: __SCREAMING_SNAKE_CASE : Any = ds['''train'''].column_names else: __SCREAMING_SNAKE_CASE : int = ds['''validation'''].column_names if data_args.image_column_name is not None: __SCREAMING_SNAKE_CASE : List[Any] = data_args.image_column_name elif "image" in column_names: __SCREAMING_SNAKE_CASE : str = '''image''' elif "img" in column_names: __SCREAMING_SNAKE_CASE : List[str] = '''img''' else: __SCREAMING_SNAKE_CASE : Tuple = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py __SCREAMING_SNAKE_CASE : Any = Compose( [ Lambda(lambda snake_case : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator __SCREAMING_SNAKE_CASE : str = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(snake_case ): __SCREAMING_SNAKE_CASE : str = [transforms(snake_case ) for image in examples[image_column_name]] __SCREAMING_SNAKE_CASE : str = [mask_generator() for i in range(len(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: __SCREAMING_SNAKE_CASE : Dict = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(snake_case ) 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: __SCREAMING_SNAKE_CASE : Union[str, Any] = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(snake_case ) # Initialize our trainer __SCREAMING_SNAKE_CASE : List[str] = Trainer( model=snake_case , args=snake_case , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=snake_case , data_collator=snake_case , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE : Tuple = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE : int = last_checkpoint __SCREAMING_SNAKE_CASE : Tuple = trainer.train(resume_from_checkpoint=snake_case ) 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: __SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.evaluate() trainer.log_metrics('''eval''' , snake_case ) trainer.save_metrics('''eval''' , snake_case ) # Write model card and (optionally) push to hub __SCREAMING_SNAKE_CASE : Optional[Any] = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''masked-image-modeling''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-image-modeling'''], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case ) else: trainer.create_model_card(**snake_case ) if __name__ == "__main__": main()
74
1
import os import sys import unittest lowercase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path lowercase_ = os.path.join(git_repo_path, """src""", """diffusers""") class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = find_backend(''' if not is_torch_available():''' ) self.assertEqual(_A , '''torch''' ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") __SCREAMING_SNAKE_CASE : List[str] = find_backend(''' if not (is_torch_available() and is_transformers_available()):''' ) self.assertEqual(_A , '''torch_and_transformers''' ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") __SCREAMING_SNAKE_CASE : List[str] = find_backend( ''' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):''' ) self.assertEqual(_A , '''torch_and_transformers_and_onnx''' ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , _A ) self.assertIn('''torch_and_transformers''' , _A ) self.assertIn('''flax_and_transformers''' , _A ) self.assertIn('''torch_and_transformers_and_onnx''' , _A ) # Likewise, we can't assert on the exact content of a key self.assertIn('''UNet2DModel''' , objects['''torch'''] ) self.assertIn('''FlaxUNet2DConditionModel''' , objects['''flax'''] ) self.assertIn('''StableDiffusionPipeline''' , objects['''torch_and_transformers'''] ) self.assertIn('''FlaxStableDiffusionPipeline''' , objects['''flax_and_transformers'''] ) self.assertIn('''LMSDiscreteScheduler''' , objects['''torch_and_scipy'''] ) self.assertIn('''OnnxStableDiffusionPipeline''' , objects['''torch_and_transformers_and_onnx'''] ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(_A , '''\nCONSTANT = None\n''' ) __SCREAMING_SNAKE_CASE : Dict = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( _A , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) __SCREAMING_SNAKE_CASE : List[Any] = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, \'torch\') @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, \'torch\') ''' __SCREAMING_SNAKE_CASE : List[Any] = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(_A , _A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, ["torch"]) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch"]) ''' __SCREAMING_SNAKE_CASE : List[str] = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , _A )
74
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_ = { """facebook/data2vec-vision-base-ft""": ( """https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json""" ), } class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = '''data2vec-vision''' def __init__( self : Optional[int] , _A : List[Any]=768 , _A : Any=12 , _A : str=12 , _A : Union[str, Any]=3072 , _A : Union[str, Any]="gelu" , _A : List[Any]=0.0 , _A : Dict=0.0 , _A : Dict=0.02 , _A : Any=1e-12 , _A : Optional[Any]=224 , _A : Union[str, Any]=16 , _A : Tuple=3 , _A : List[Any]=False , _A : List[str]=False , _A : Dict=False , _A : Dict=False , _A : Any=0.1 , _A : List[str]=0.1 , _A : Dict=True , _A : Dict=[3, 5, 7, 11] , _A : Union[str, Any]=[1, 2, 3, 6] , _A : Optional[Any]=True , _A : Any=0.4 , _A : List[str]=256 , _A : Any=1 , _A : Any=False , _A : Union[str, Any]=255 , **_A : Tuple , ): """simple docstring""" super().__init__(**_A ) __SCREAMING_SNAKE_CASE : Any = hidden_size __SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Tuple = num_attention_heads __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Tuple = hidden_act __SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : int = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps __SCREAMING_SNAKE_CASE : Any = image_size __SCREAMING_SNAKE_CASE : Optional[int] = patch_size __SCREAMING_SNAKE_CASE : Any = num_channels __SCREAMING_SNAKE_CASE : List[str] = use_mask_token __SCREAMING_SNAKE_CASE : List[Any] = use_absolute_position_embeddings __SCREAMING_SNAKE_CASE : Dict = use_relative_position_bias __SCREAMING_SNAKE_CASE : str = use_shared_relative_position_bias __SCREAMING_SNAKE_CASE : Union[str, Any] = layer_scale_init_value __SCREAMING_SNAKE_CASE : str = drop_path_rate __SCREAMING_SNAKE_CASE : Tuple = use_mean_pooling # decode head attributes (semantic segmentation) __SCREAMING_SNAKE_CASE : str = out_indices __SCREAMING_SNAKE_CASE : List[str] = pool_scales # auxiliary head attributes (semantic segmentation) __SCREAMING_SNAKE_CASE : Tuple = use_auxiliary_head __SCREAMING_SNAKE_CASE : Optional[Any] = auxiliary_loss_weight __SCREAMING_SNAKE_CASE : Union[str, Any] = auxiliary_channels __SCREAMING_SNAKE_CASE : List[Any] = auxiliary_num_convs __SCREAMING_SNAKE_CASE : Optional[Any] = auxiliary_concat_input __SCREAMING_SNAKE_CASE : Any = semantic_loss_ignore_index class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = version.parse('''1.11''' ) @property def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return 1e-4
74
1
class __UpperCamelCase : """simple docstring""" def __init__( self : Optional[Any] , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = arr.split(''',''' ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = [int(self.array[0] )] * len(self.array ) __SCREAMING_SNAKE_CASE : List[str] = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): __SCREAMING_SNAKE_CASE : Union[str, Any] = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": lowercase_ = input("""please input some numbers:""") lowercase_ = SubArray(whole_array) lowercase_ = array.solve_sub_array() print(("""the results is:""", re))
74
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[str] , _A : Optional[int] , _A : Optional[Any]=13 , _A : List[Any]=7 , _A : List[str]=True , _A : Dict=True , _A : Tuple=False , _A : Union[str, Any]=True , _A : List[str]=99 , _A : Union[str, Any]=32 , _A : str=5 , _A : Union[str, Any]=4 , _A : int=37 , _A : int="gelu" , _A : Tuple=0.1 , _A : Dict=0.1 , _A : Optional[Any]=512 , _A : str=16 , _A : List[Any]=2 , _A : List[Any]=0.02 , _A : Any=3 , _A : Optional[int]=4 , _A : Optional[int]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : str = seq_length __SCREAMING_SNAKE_CASE : int = is_training __SCREAMING_SNAKE_CASE : Union[str, Any] = use_input_mask __SCREAMING_SNAKE_CASE : str = use_token_type_ids __SCREAMING_SNAKE_CASE : Any = use_labels __SCREAMING_SNAKE_CASE : Any = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : Any = num_hidden_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads __SCREAMING_SNAKE_CASE : List[str] = intermediate_size __SCREAMING_SNAKE_CASE : List[str] = hidden_act __SCREAMING_SNAKE_CASE : int = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings __SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : List[Any] = num_labels __SCREAMING_SNAKE_CASE : List[Any] = num_choices __SCREAMING_SNAKE_CASE : Union[str, Any] = scope def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : Any = None __SCREAMING_SNAKE_CASE : Union[str, Any] = None __SCREAMING_SNAKE_CASE : int = None if self.use_labels: __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Optional[int] , _A : int , _A : Union[str, Any] , _A : List[str] , _A : Dict , _A : Dict , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Tuple , _A : Dict , _A : Tuple , _A : str , _A : Optional[int] , _A : List[str] , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForMaskedLM(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = 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 : Dict , _A : Optional[Any] , _A : Optional[Any] , _A : Union[str, Any] , _A : Optional[Any] , _A : str , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : int = 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 : Dict , _A : List[str] , _A : Tuple , _A : str , _A : Tuple , _A : Optional[int] , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels __SCREAMING_SNAKE_CASE : List[Any] = DistilBertForSequenceClassification(_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : List[str] , _A : int , _A : List[Any] , _A : Any , _A : Any , _A : str , _A : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels __SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertForTokenClassification(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : Dict = 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 : Dict , _A : Optional[int] , _A : int , _A : Optional[int] , _A : List[Any] , _A : int , _A : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.num_choices __SCREAMING_SNAKE_CASE : int = DistilBertForMultipleChoice(config=_A ) model.to(_A ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Any = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE : Optional[Any] = model( _A , attention_mask=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() ((__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE), (__SCREAMING_SNAKE_CASE)) : List[Any] = config_and_inputs __SCREAMING_SNAKE_CASE : Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) lowerCAmelCase_ = ( { '''feature-extraction''': DistilBertModel, '''fill-mask''': DistilBertForMaskedLM, '''question-answering''': DistilBertForQuestionAnswering, '''text-classification''': DistilBertForSequenceClassification, '''token-classification''': DistilBertForTokenClassification, '''zero-shot''': DistilBertForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = True def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = DistilBertModelTester(self ) __SCREAMING_SNAKE_CASE : List[str] = ConfigTester(self , config_class=_A , dim=37 ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*_A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*_A ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*_A ) def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*_A ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @slow @require_torch_gpu def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return __SCREAMING_SNAKE_CASE : Dict = True __SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(config=_A ) __SCREAMING_SNAKE_CASE : int = self._prepare_for_class(_A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = torch.jit.trace( _A , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_A , os.path.join(_A , '''traced_model.pt''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.jit.load(os.path.join(_A , '''traced_model.pt''' ) , map_location=_A ) loaded(inputs_dict['''input_ids'''].to(_A ) , inputs_dict['''attention_mask'''].to(_A ) ) @require_torch class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = DistilBertModel.from_pretrained('''distilbert-base-uncased''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_A , attention_mask=_A )[0] __SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _A ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1e-4 ) )
74
1
from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, 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_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowercase_ = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase__ ) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : Union[str, Any] , *_A : str , **_A : Any ): """simple docstring""" super().__init__(*_A , **_A ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def UpperCAmelCase__ ( self : List[Any] , _A : Optional[int]=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = {} if top_k is not None: __SCREAMING_SNAKE_CASE : str = top_k return {}, {}, postprocess_params def __call__( self : Optional[int] , _A : Union[str, List[str], "Image.Image", List["Image.Image"]] , **_A : int ): """simple docstring""" return super().__call__(_A , **_A ) def UpperCAmelCase__ ( self : Optional[Any] , _A : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = load_image(_A ) __SCREAMING_SNAKE_CASE : List[str] = self.image_processor(images=_A , return_tensors=self.framework ) return model_inputs def UpperCAmelCase__ ( self : Optional[int] , _A : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.model(**_A ) return model_outputs def UpperCAmelCase__ ( self : int , _A : Any , _A : str=5 ): """simple docstring""" if top_k > self.model.config.num_labels: __SCREAMING_SNAKE_CASE : str = self.model.config.num_labels if self.framework == "pt": __SCREAMING_SNAKE_CASE : Dict = model_outputs.logits.softmax(-1 )[0] __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = probs.topk(_A ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE : Union[str, Any] = stable_softmax(model_outputs.logits , axis=-1 )[0] __SCREAMING_SNAKE_CASE : Tuple = tf.math.top_k(_A , k=_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Any = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = scores.tolist() __SCREAMING_SNAKE_CASE : Union[str, Any] = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_A , _A )]
74
import logging import os import threading import time try: import warnings except ImportError: lowercase_ = None try: import msvcrt except ImportError: lowercase_ = None try: import fcntl except ImportError: lowercase_ = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowercase_ = OSError # Data # ------------------------------------------------ lowercase_ = [ """Timeout""", """BaseFileLock""", """WindowsFileLock""", """UnixFileLock""", """SoftFileLock""", """FileLock""", ] lowercase_ = """3.0.12""" lowercase_ = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE : Optional[Any] = _logger or logging.getLogger(__name__ ) return _logger class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[Any] , _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = lock_file return None def __str__( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = F'''The file lock \'{self.lock_file}\' could not be acquired.''' return temp class __UpperCamelCase : """simple docstring""" def __init__( self : Optional[Any] , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = lock return None def __enter__( self : Any ): """simple docstring""" return self.lock def __exit__( self : str , _A : Any , _A : int , _A : Any ): """simple docstring""" self.lock.release() return None class __UpperCamelCase : """simple docstring""" def __init__( self : Any , _A : int , _A : Optional[int]=-1 , _A : List[Any]=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE : Optional[Any] = self.hash_filename_if_too_long(_A , _A ) # The path to the lock file. __SCREAMING_SNAKE_CASE : Tuple = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE : str = None # The default timeout value. __SCREAMING_SNAKE_CASE : Any = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE : int = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE : int = 0 return None @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : Tuple , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = float(_A ) return None def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Tuple , _A : List[Any]=None , _A : Optional[Any]=0.05 ): """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE : Optional[int] = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE : Tuple = id(self ) __SCREAMING_SNAKE_CASE : Any = self._lock_file __SCREAMING_SNAKE_CASE : Union[str, Any] = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(F'''Attempting to acquire lock {lock_id} on {lock_filename}''' ) self._acquire() if self.is_locked: logger().debug(F'''Lock {lock_id} acquired on {lock_filename}''' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(F'''Timeout on acquiring lock {lock_id} on {lock_filename}''' ) raise Timeout(self._lock_file ) else: logger().debug( F'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...''' ) time.sleep(_A ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE : Optional[Any] = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : int , _A : List[str]=False ): """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE : Optional[int] = id(self ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self._lock_file logger().debug(F'''Attempting to release lock {lock_id} on {lock_filename}''' ) self._release() __SCREAMING_SNAKE_CASE : int = 0 logger().debug(F'''Lock {lock_id} released on {lock_filename}''' ) return None def __enter__( self : int ): """simple docstring""" self.acquire() return self def __exit__( self : Optional[int] , _A : List[str] , _A : List[Any] , _A : int ): """simple docstring""" self.release() return None def __del__( self : int ): """simple docstring""" self.release(force=_A ) return None def UpperCAmelCase__ ( self : Optional[int] , _A : str , _A : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = os.path.basename(_A ) if len(_A ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE : Tuple = os.path.dirname(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = str(hash(_A ) ) __SCREAMING_SNAKE_CASE : Optional[int] = filename[: max_length - len(_A ) - 8] + '''...''' + hashed_filename + '''.lock''' return os.path.join(_A , _A ) else: return path class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[Any] , _A : Optional[Any] , _A : List[Any]=-1 , _A : Dict=None ): """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(_A , timeout=_A , max_filename_length=_A ) __SCREAMING_SNAKE_CASE : str = '''\\\\?\\''' + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE : List[str] = os.open(self._lock_file , _A ) except OSError: pass else: try: msvcrt.locking(_A , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(_A ) else: __SCREAMING_SNAKE_CASE : str = fd return None def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self._lock_file_fd __SCREAMING_SNAKE_CASE : int = None msvcrt.locking(_A , msvcrt.LK_UNLCK , 1 ) os.close(_A ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : Tuple , _A : Optional[int] , _A : Dict=-1 , _A : str=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = os.statvfs(os.path.dirname(_A ) ).f_namemax super().__init__(_A , timeout=_A , max_filename_length=_A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE : int = os.open(self._lock_file , _A ) try: fcntl.flock(_A , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(_A ) else: __SCREAMING_SNAKE_CASE : int = fd return None def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self._lock_file_fd __SCREAMING_SNAKE_CASE : Any = None fcntl.flock(_A , fcntl.LOCK_UN ) os.close(_A ) return None class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE : Optional[Any] = os.open(self._lock_file , _A ) except OSError: pass else: __SCREAMING_SNAKE_CASE : List[str] = fd return None def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE : Optional[Any] = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowercase_ = None if msvcrt: lowercase_ = WindowsFileLock elif fcntl: lowercase_ = UnixFileLock else: lowercase_ = SoftFileLock if warnings is not None: warnings.warn("""only soft file lock is available""")
74
1
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = 1 @register_to_config def __init__( self : List[str] , _A : int = 1000 , _A : Optional[Union[np.ndarray, List[float]]] = None ): """simple docstring""" self.set_timesteps(_A ) # standard deviation of the initial noise distribution __SCREAMING_SNAKE_CASE : Union[str, Any] = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. __SCREAMING_SNAKE_CASE : Any = 4 # running values __SCREAMING_SNAKE_CASE : Tuple = [] def UpperCAmelCase__ ( self : Dict , _A : int , _A : Union[str, torch.device] = None ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = num_inference_steps __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: __SCREAMING_SNAKE_CASE : Optional[int] = torch.sin(steps * math.pi / 2 ) ** 2 __SCREAMING_SNAKE_CASE : Union[str, Any] = (1.0 - self.betas**2) ** 0.5 __SCREAMING_SNAKE_CASE : str = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] __SCREAMING_SNAKE_CASE : List[Any] = timesteps.to(_A ) __SCREAMING_SNAKE_CASE : Any = [] def UpperCAmelCase__ ( self : int , _A : torch.FloatTensor , _A : int , _A : torch.FloatTensor , _A : bool = True , ): """simple docstring""" if self.num_inference_steps is None: raise ValueError( '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = (self.timesteps == timestep).nonzero().item() __SCREAMING_SNAKE_CASE : Optional[int] = timestep_index + 1 __SCREAMING_SNAKE_CASE : Union[str, Any] = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(_A ) if len(self.ets ) == 1: __SCREAMING_SNAKE_CASE : Any = self.ets[-1] elif len(self.ets ) == 2: __SCREAMING_SNAKE_CASE : str = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: __SCREAMING_SNAKE_CASE : Dict = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: __SCREAMING_SNAKE_CASE : int = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) __SCREAMING_SNAKE_CASE : str = self._get_prev_sample(_A , _A , _A , _A ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_A ) def UpperCAmelCase__ ( self : str , _A : torch.FloatTensor , *_A : Any , **_A : List[Any] ): """simple docstring""" return sample def UpperCAmelCase__ ( self : Dict , _A : Any , _A : Optional[Any] , _A : str , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = self.alphas[timestep_index] __SCREAMING_SNAKE_CASE : Tuple = self.betas[timestep_index] __SCREAMING_SNAKE_CASE : int = self.alphas[prev_timestep_index] __SCREAMING_SNAKE_CASE : str = self.betas[prev_timestep_index] __SCREAMING_SNAKE_CASE : List[Any] = (sample - sigma * ets) / max(_A , 1e-8 ) __SCREAMING_SNAKE_CASE : Optional[int] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : str ): """simple docstring""" return self.config.num_train_timesteps
74
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup lowercase_ = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : Optional[Any] , **_A : Dict ): """simple docstring""" requires_backends(self , ['''bs4'''] ) super().__init__(**_A ) def UpperCAmelCase__ ( self : Optional[int] , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = [] __SCREAMING_SNAKE_CASE : Any = [] __SCREAMING_SNAKE_CASE : Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag __SCREAMING_SNAKE_CASE : Optional[int] = parent.find_all(child.name , recursive=_A ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(_A ) else next(i for i, s in enumerate(_A , 1 ) if s is child ) ) __SCREAMING_SNAKE_CASE : Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def UpperCAmelCase__ ( self : Dict , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BeautifulSoup(_A , '''html.parser''' ) __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Optional[Any] = [] __SCREAMING_SNAKE_CASE : int = [] for element in html_code.descendants: if type(_A ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue __SCREAMING_SNAKE_CASE : List[Any] = html.unescape(_A ).strip() if not text_in_this_tag: continue all_doc_strings.append(_A ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = self.xpath_soup(_A ) stringaxtag_seq.append(_A ) stringaxsubs_seq.append(_A ) if len(_A ) != len(_A ): raise ValueError('''Number of doc strings and xtags does not correspond''' ) if len(_A ) != len(_A ): raise ValueError('''Number of doc strings and xsubs does not correspond''' ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def UpperCAmelCase__ ( self : int , _A : Tuple , _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = '''''' for tagname, subs in zip(_A , _A ): xpath += F'''/{tagname}''' if subs != 0: xpath += F'''[{subs}]''' return xpath def __call__( self : Optional[int] , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = False # Check that strings has a valid type if isinstance(_A , _A ): __SCREAMING_SNAKE_CASE : Any = True elif isinstance(_A , (list, tuple) ): if len(_A ) == 0 or isinstance(html_strings[0] , _A ): __SCREAMING_SNAKE_CASE : List[Any] = True if not valid_strings: raise ValueError( '''HTML strings must of type `str`, `List[str]` (batch of examples), ''' F'''but is of type {type(_A )}.''' ) __SCREAMING_SNAKE_CASE : Any = bool(isinstance(_A , (list, tuple) ) and (isinstance(html_strings[0] , _A )) ) if not is_batched: __SCREAMING_SNAKE_CASE : Dict = [html_strings] # Get nodes + xpaths __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Tuple = [] for html_string in html_strings: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_three_from_single(_A ) nodes.append(_A ) __SCREAMING_SNAKE_CASE : Dict = [] for node, tag_list, sub_list in zip(_A , _A , _A ): __SCREAMING_SNAKE_CASE : List[Any] = self.construct_xpath(_A , _A ) xpath_strings.append(_A ) xpaths.append(_A ) # return as Dict __SCREAMING_SNAKE_CASE : Optional[int] = {'''nodes''': nodes, '''xpaths''': xpaths} __SCREAMING_SNAKE_CASE : List[str] = BatchFeature(data=_A , tensor_type=_A ) return encoded_inputs
74
1
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def a__ ( snake_case = True , *snake_case , **snake_case ): """simple docstring""" if not is_tqdm_available(): raise ImportError('''Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.''' ) __SCREAMING_SNAKE_CASE : List[Any] = False if main_process_only: __SCREAMING_SNAKE_CASE : Tuple = PartialState().local_process_index == 0 return _tqdm(*snake_case , **snake_case , disable=snake_case )
74
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() def a__ ( snake_case , snake_case , snake_case , snake_case , snake_case = True ): """simple docstring""" print(F'''Converting {name}...''' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": __SCREAMING_SNAKE_CASE : Tuple = timm.create_model('''levit_128s''' , pretrained=snake_case ) else: __SCREAMING_SNAKE_CASE : Any = timm.create_model('''levit_128''' , pretrained=snake_case ) if hidden_sizes == 192: __SCREAMING_SNAKE_CASE : Dict = timm.create_model('''levit_192''' , pretrained=snake_case ) if hidden_sizes == 256: __SCREAMING_SNAKE_CASE : Optional[int] = timm.create_model('''levit_256''' , pretrained=snake_case ) if hidden_sizes == 384: __SCREAMING_SNAKE_CASE : Any = timm.create_model('''levit_384''' , pretrained=snake_case ) from_model.eval() __SCREAMING_SNAKE_CASE : str = LevitForImageClassificationWithTeacher(snake_case ).eval() __SCREAMING_SNAKE_CASE : int = OrderedDict() __SCREAMING_SNAKE_CASE : List[Any] = from_model.state_dict() __SCREAMING_SNAKE_CASE : Tuple = list(from_model.state_dict().keys() ) __SCREAMING_SNAKE_CASE : str = list(our_model.state_dict().keys() ) print(len(snake_case ) , len(snake_case ) ) for i in range(len(snake_case ) ): __SCREAMING_SNAKE_CASE : int = weights[og_keys[i]] our_model.load_state_dict(snake_case ) __SCREAMING_SNAKE_CASE : str = torch.randn((2, 3, 224, 224) ) __SCREAMING_SNAKE_CASE : Tuple = from_model(snake_case ) __SCREAMING_SNAKE_CASE : List[str] = our_model(snake_case ).logits assert torch.allclose(snake_case , snake_case ), "The model logits don't match the original one." __SCREAMING_SNAKE_CASE : Union[str, Any] = name print(snake_case ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __SCREAMING_SNAKE_CASE : Union[str, Any] = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F'''Pushed {checkpoint_name}''' ) def a__ ( snake_case , snake_case = None , snake_case = True ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = '''imagenet-1k-id2label.json''' __SCREAMING_SNAKE_CASE : int = 1_000 __SCREAMING_SNAKE_CASE : Optional[int] = (1, num_labels) __SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' __SCREAMING_SNAKE_CASE : Optional[Any] = num_labels __SCREAMING_SNAKE_CASE : List[Any] = json.load(open(hf_hub_download(snake_case , snake_case , repo_type='''dataset''' ) , '''r''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {int(snake_case ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : str = idalabel __SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : List[str] = partial(snake_case , num_labels=snake_case , idalabel=snake_case , labelaid=snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''levit-128S''': 128, '''levit-128''': 128, '''levit-192''': 192, '''levit-256''': 256, '''levit-384''': 384, } __SCREAMING_SNAKE_CASE : Optional[int] = { '''levit-128S''': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), '''levit-128''': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), '''levit-192''': ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), '''levit-256''': ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), '''levit-384''': ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , snake_case , names_to_config[model_name] , snake_case , snake_case ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , snake_case , snake_case , snake_case , snake_case ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help="""The name of the model you wish to convert, it must be one of the supported Levit* architecture,""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""levit-dump-folder/""", type=Path, required=False, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
74
1
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = DebertaVaTokenizer lowerCAmelCase_ = DebertaVaTokenizerFast lowerCAmelCase_ = True lowerCAmelCase_ = True def UpperCAmelCase__ ( self : Dict ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE : str = DebertaVaTokenizer(_A , unk_token='''<unk>''' ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Union[str, Any] , _A : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = '''this is a test''' __SCREAMING_SNAKE_CASE : Dict = '''this is a test''' return input_text, output_text def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = '''<pad>''' __SCREAMING_SNAKE_CASE : Optional[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''[PAD]''' ) self.assertEqual(len(_A ) , 3_0001 ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0000 ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = ''' \tHeLLo!how \n Are yoU? ''' __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''▁hello''', '''!''', '''how''', '''▁are''', '''▁you''', '''?'''] # fmt: on __SCREAMING_SNAKE_CASE : List[str] = DebertaVaTokenizer(_A , do_lower_case=_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Tuple = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" pass @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = '''I was born in 92000, and this is falsé.''' __SCREAMING_SNAKE_CASE : Optional[int] = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on __SCREAMING_SNAKE_CASE : Any = DebertaVaTokenizer(_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Tuple = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : Tuple = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = '''I was born in 92000, and this is falsé.''' __SCREAMING_SNAKE_CASE : Optional[Any] = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on __SCREAMING_SNAKE_CASE : List[str] = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : str = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = '''I was born in 92000, and this is falsé.''' __SCREAMING_SNAKE_CASE : List[str] = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on __SCREAMING_SNAKE_CASE : Union[str, Any] = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Optional[int] = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = '''I was born in 92000, and this is falsé.''' __SCREAMING_SNAKE_CASE : Optional[int] = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on __SCREAMING_SNAKE_CASE : Optional[int] = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : Any = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = ''' \tHeLLo!how \n Are yoU? ''' __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''▁''', '''<unk>''', '''e''', '''<unk>''', '''o''', '''!''', '''how''', '''▁''', '''<unk>''', '''re''', '''▁yo''', '''<unk>''', '''?'''] # fmt: on __SCREAMING_SNAKE_CASE : Tuple = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Dict = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Any = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Dict = '''I was born in 92000, and this is falsé.''' __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : str = tokenizer.encode(_A , add_special_tokens=_A ) __SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode(_A ) __SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = '''This is a test''' __SCREAMING_SNAKE_CASE : str = [13, 1, 4398, 25, 21, 1289] __SCREAMING_SNAKE_CASE : Any = ['''▁''', '''T''', '''his''', '''▁is''', '''▁a''', '''▁test'''] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''▁''', '''<unk>''', '''his''', '''▁is''', '''▁a''', '''▁test'''] __SCREAMING_SNAKE_CASE : List[str] = DebertaVaTokenizer(_A , keep_accents=_A ) __SCREAMING_SNAKE_CASE : Dict = DebertaVaTokenizerFast(_A , keep_accents=_A ) __SCREAMING_SNAKE_CASE : int = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : str = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Dict = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Any = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __SCREAMING_SNAKE_CASE : int = '''I was born in 92000, and this is falsé.''' __SCREAMING_SNAKE_CASE : Union[str, Any] = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] __SCREAMING_SNAKE_CASE : str = ['''▁''', '''I''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.''', ] __SCREAMING_SNAKE_CASE : Tuple = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = DebertaVaTokenizer(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode('''sequence builders''' ) __SCREAMING_SNAKE_CASE : Any = tokenizer.encode('''multi-sequence build''' ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.build_inputs_with_special_tokens(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , _A ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , _A , ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = {'''input_ids''': [[1, 3_9867, 36, 1_9390, 486, 27, 3_5052, 8_1436, 18, 6_0685, 1225, 7, 3_5052, 8_1436, 18, 9367, 1_6899, 18, 1_5937, 53, 594, 773, 18, 1_6287, 3_0465, 36, 1_5937, 6, 4_1139, 38, 3_6979, 6_0763, 191, 6, 3_4132, 99, 6, 5_0538, 390, 4_3230, 6, 3_4132, 2779, 2_0850, 14, 699, 1072, 1194, 36, 382, 1_0901, 53, 7, 699, 1072, 2084, 36, 2_0422, 630, 53, 19, 105, 3049, 1896, 1053, 1_6899, 1506, 11, 3_7978, 4243, 7, 1237, 3_1869, 200, 1_6566, 654, 6, 3_5052, 8_1436, 7, 5_5630, 1_3593, 4, 2], [1, 26, 1_5011, 13, 667, 8, 1053, 18, 2_3611, 1237, 7_2356, 1_2820, 34, 10_4134, 1209, 35, 1_3313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 1_5785, 1_4951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='''microsoft/deberta-v2-xlarge''' , revision='''ad6e42c1532ddf3a15c39246b63f5559d558b670''' , )
74
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase_ = { """configuration_falcon""": ["""FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FalconConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FALCON_PRETRAINED_MODEL_ARCHIVE_LIST""", """FalconForCausalLM""", """FalconModel""", """FalconPreTrainedModel""", """FalconForSequenceClassification""", """FalconForTokenClassification""", """FalconForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
74
1
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = get_aligned_output_features_output_indices(_A , _A , _A ) self.assertEqual(_A , ['''c'''] ) self.assertEqual(_A , [2] ) # Out indices set to match out features __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = get_aligned_output_features_output_indices(['''a''', '''c'''] , _A , _A ) self.assertEqual(_A , ['''a''', '''c'''] ) self.assertEqual(_A , [0, 2] ) # Out features set to match out indices __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = get_aligned_output_features_output_indices(_A , [0, 2] , _A ) self.assertEqual(_A , ['''a''', '''c'''] ) self.assertEqual(_A , [0, 2] ) # Out features selected from negative indices __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Any = get_aligned_output_features_output_indices(_A , [-3, -1] , _A ) self.assertEqual(_A , ['''a''', '''c'''] ) self.assertEqual(_A , [-3, -1] ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" with self.assertRaises(_A ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , _A ) # Out features must be a list with self.assertRaises(_A ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(_A ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(_A ): verify_out_features_out_indices(_A , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(_A ): verify_out_features_out_indices(_A , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(_A ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(_A ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(_A ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BackboneMixin() __SCREAMING_SNAKE_CASE : Any = ['''a''', '''b''', '''c'''] __SCREAMING_SNAKE_CASE : List[Any] = ['''a''', '''c'''] __SCREAMING_SNAKE_CASE : int = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly __SCREAMING_SNAKE_CASE : Optional[Any] = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) __SCREAMING_SNAKE_CASE : str = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
74
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging lowercase_ = logging.get_logger(__name__) def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = set() __SCREAMING_SNAKE_CASE : str = [] def parse_line(snake_case ): for line in fp: if isinstance(snake_case , snake_case ): __SCREAMING_SNAKE_CASE : List[Any] = line.decode('''UTF-8''' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(''' ''' ): # process a single warning and move it to `selected_warnings`. if len(snake_case ) > 0: __SCREAMING_SNAKE_CASE : List[Any] = '''\n'''.join(snake_case ) # Only keep the warnings specified in `targets` if any(F''': {x}: ''' in warning for x in targets ): selected_warnings.add(snake_case ) buffer.clear() continue else: __SCREAMING_SNAKE_CASE : int = line.strip() buffer.append(snake_case ) if from_gh: for filename in os.listdir(snake_case ): __SCREAMING_SNAKE_CASE : Any = os.path.join(snake_case , snake_case ) if not os.path.isdir(snake_case ): # read the file if filename != "warnings.txt": continue with open(snake_case ) as fp: parse_line(snake_case ) else: try: with zipfile.ZipFile(snake_case ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case ): # read the file if filename != "warnings.txt": continue with z.open(snake_case ) as fp: parse_line(snake_case ) except Exception: logger.warning( F'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' ) return selected_warnings def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = set() __SCREAMING_SNAKE_CASE : List[Any] = [os.path.join(snake_case , snake_case ) for p in os.listdir(snake_case ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(snake_case , snake_case ) ) return selected_warnings if __name__ == "__main__": def a__ ( snake_case ): """simple docstring""" return values.split(''',''' ) lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) lowercase_ = parser.parse_args() lowercase_ = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links lowercase_ = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts lowercase_ = extract_warnings(args.output_dir, args.targets) lowercase_ = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
74
1