code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCAmelCase: List[str] = logging.get_logger(__name__) _lowerCAmelCase: Tuple = torch.device('cpu') def _lowercase( ): a__ ='http://images.cocodataset.org/val2017/000000039769.jpg' a__ =Image.open(requests.get(__a , stream=__a ).raw ) return im def _lowercase( __a : Optional[Any] ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1703e00, 2.1107e00, -2.0811e00, 8.8685e-01, 2.4360e-01] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9636e-01, 2.3478e-01, -1.6963e00, -1.7381e00, -8.6337e-01] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2768e-01, -4.7429e-01, -1.0897e00, -1.0248e00, 3.5523e-02] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5330e-01, 2.4211e-01, -6.0185e-01, -8.2789e-01, -6.0446e-02] ) def _lowercase( __a : int , __a : int , __a : Optional[Any] ): a__ =dct.pop(__a ) a__ =val def _lowercase( __a : Optional[Any] ): a__ =[] for k in state_dict.keys(): a__ =k if ".pwconv" in k: a__ =k_new.replace('.pwconv' , '.point_wise_conv' ) if ".dwconv" in k: a__ =k_new.replace('.dwconv' , '.depth_wise_conv' ) if ".Proj." in k: a__ =k_new.replace('.Proj.' , '.proj.' ) if "patch_embed" in k_new: a__ =k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' ) if "network" in k_new: a__ =k_new.split('.' ) if ls[2].isdigit(): a__ ='swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] ) else: a__ =k_new.replace('network' , 'swiftformer.encoder.network' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def _lowercase( __a : Union[str, Any] , __a : int , __a : str ): a__ =SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size a__ =1000 a__ ='huggingface/label-files' a__ ='imagenet-1k-id2label.json' a__ =json.load(open(hf_hub_download(__a , __a , repo_type='dataset' ) , 'r' ) ) a__ ={int(__a ): v for k, v in idalabel.items()} a__ =idalabel a__ ={v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": a__ =[3, 3, 6, 4] a__ =[48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": a__ =[3, 3, 9, 6] a__ =[48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": a__ =[4, 3, 10, 5] a__ =[48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": a__ =[4, 4, 12, 6] a__ =[64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('https' ): a__ =torch.hub.load_state_dict_from_url(__a , map_location='cpu' , check_hash=__a ) else: a__ =torch.load(__a , map_location='cpu' ) a__ =checkpoint a__ =create_rename_keys(__a ) for rename_key_src, rename_key_dest in rename_keys: rename_key(__a , __a , __a ) # load HuggingFace model a__ =SwiftFormerForImageClassification(__a ).eval() hf_model.load_state_dict(__a ) # prepare test inputs a__ =prepare_img() a__ =ViTImageProcessor.from_pretrained('preprocessor_config' ) a__ =processor(images=__a , return_tensors='pt' ) # compare outputs from both models a__ =get_expected_output(__a ) a__ =hf_model(inputs['pixel_values'] ).logits assert hf_logits.shape == torch.Size([1, 1000] ) assert torch.allclose(hf_logits[0, 0:5] , __a , atol=1e-3 ) Path(__a ).mkdir(exist_ok=__a ) print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(__a ) if __name__ == "__main__": _lowerCAmelCase: Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swiftformer_name', default='swiftformer_xs', choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'], type=str, help='Name of the SwiftFormer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='./converted_outputs/', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.') _lowerCAmelCase: Optional[int] = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
20
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def a_ ( lowerCamelCase : Any ): # vision encoder if "img_encoder.pos_embed" in name: lowerCAmelCase = name.replace('img_encoder.pos_embed' , 'vision_model.embeddings.position_embeddings' ) if "img_encoder.patch_embed.proj" in name: lowerCAmelCase = name.replace('img_encoder.patch_embed.proj' , 'vision_model.embeddings.patch_embeddings.projection' ) if "img_encoder.patch_embed.norm" in name: lowerCAmelCase = name.replace('img_encoder.patch_embed.norm' , 'vision_model.embeddings.layernorm' ) if "img_encoder.layers" in name: lowerCAmelCase = name.replace('img_encoder.layers' , 'vision_model.encoder.stages' ) if "blocks" in name and "res" not in name: lowerCAmelCase = name.replace('blocks' , 'layers' ) if "attn" in name and "pre_assign" not in name: lowerCAmelCase = name.replace('attn' , 'self_attn' ) if "proj" in name and "self_attn" in name and "text" not in name: lowerCAmelCase = name.replace('proj' , 'out_proj' ) if "pre_assign_attn.attn.proj" in name: lowerCAmelCase = name.replace('pre_assign_attn.attn.proj' , 'pre_assign_attn.attn.out_proj' ) if "norm1" in name: lowerCAmelCase = name.replace('norm1' , 'layer_norm1' ) if "norm2" in name and "pre_assign" not in name: lowerCAmelCase = name.replace('norm2' , 'layer_norm2' ) if "img_encoder.norm" in name: lowerCAmelCase = name.replace('img_encoder.norm' , 'vision_model.layernorm' ) # text encoder if "text_encoder.token_embedding" in name: lowerCAmelCase = name.replace('text_encoder.token_embedding' , 'text_model.embeddings.token_embedding' ) if "text_encoder.positional_embedding" in name: lowerCAmelCase = name.replace('text_encoder.positional_embedding' , 'text_model.embeddings.position_embedding.weight' ) if "text_encoder.transformer.resblocks." in name: lowerCAmelCase = name.replace('text_encoder.transformer.resblocks.' , 'text_model.encoder.layers.' ) if "ln_1" in name: lowerCAmelCase = name.replace('ln_1' , 'layer_norm1' ) if "ln_2" in name: lowerCAmelCase = name.replace('ln_2' , 'layer_norm2' ) if "c_fc" in name: lowerCAmelCase = name.replace('c_fc' , 'fc1' ) if "c_proj" in name: lowerCAmelCase = name.replace('c_proj' , 'fc2' ) if "text_encoder" in name: lowerCAmelCase = name.replace('text_encoder' , 'text_model' ) if "ln_final" in name: lowerCAmelCase = name.replace('ln_final' , 'final_layer_norm' ) # projection layers if "img_projector.linear_hidden." in name: lowerCAmelCase = name.replace('img_projector.linear_hidden.' , 'visual_projection.' ) if "img_projector.linear_out." in name: lowerCAmelCase = name.replace('img_projector.linear_out.' , 'visual_projection.3.' ) if "text_projector.linear_hidden" in name: lowerCAmelCase = name.replace('text_projector.linear_hidden' , 'text_projection' ) if "text_projector.linear_out" in name: lowerCAmelCase = name.replace('text_projector.linear_out' , 'text_projection.3' ) return name def a_ ( lowerCamelCase : Tuple , lowerCamelCase : List[Any] ): for key in orig_state_dict.copy().keys(): lowerCAmelCase = orig_state_dict.pop(lowerCamelCase ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase = key.split('.' ) lowerCAmelCase , lowerCAmelCase = int(key_split[2] ), int(key_split[4] ) lowerCAmelCase = config.vision_config.hidden_size if "weight" in key: lowerCAmelCase = val[:dim, :] lowerCAmelCase = val[dim : dim * 2, :] lowerCAmelCase = val[-dim:, :] else: lowerCAmelCase = val[:dim] lowerCAmelCase = val[dim : dim * 2] lowerCAmelCase = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase = key.split('.' ) lowerCAmelCase = int(key_split[3] ) lowerCAmelCase = config.text_config.hidden_size if "weight" in key: lowerCAmelCase = val[:dim, :] lowerCAmelCase = val[ dim : dim * 2, : ] lowerCAmelCase = val[-dim:, :] else: lowerCAmelCase = val[:dim] lowerCAmelCase = val[dim : dim * 2] lowerCAmelCase = val[-dim:] else: lowerCAmelCase = rename_key(lowerCamelCase ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): lowerCAmelCase = val.squeeze_() else: lowerCAmelCase = val return orig_state_dict def a_ ( ): lowerCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' lowerCAmelCase = Image.open(requests.get(lowerCamelCase , stream=lowerCamelCase ).raw ) return im @torch.no_grad() def a_ ( lowerCamelCase : str , lowerCamelCase : Optional[int] , lowerCamelCase : Dict="groupvit-gcc-yfcc" , lowerCamelCase : Dict=False ): lowerCAmelCase = GroupViTConfig() lowerCAmelCase = GroupViTModel(lowerCamelCase ).eval() lowerCAmelCase = torch.load(lowerCamelCase , map_location='cpu' )['model'] lowerCAmelCase = convert_state_dict(lowerCamelCase , lowerCamelCase ) lowerCAmelCase , lowerCAmelCase = model.load_state_dict(lowerCamelCase , strict=lowerCamelCase ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowerCamelCase ) == 0) # verify result lowerCAmelCase = CLIPProcessor.from_pretrained('openai/clip-vit-base-patch32' ) lowerCAmelCase = prepare_img() lowerCAmelCase = processor(text=['a photo of a cat', 'a photo of a dog'] , images=lowerCamelCase , padding=lowerCamelCase , return_tensors='pt' ) with torch.no_grad(): lowerCAmelCase = model(**lowerCamelCase ) if model_name == "groupvit-gcc-yfcc": lowerCAmelCase = torch.tensor([[13.3_523, 6.3_629]] ) elif model_name == "groupvit-gcc-redcaps": lowerCAmelCase = torch.tensor([[16.1_873, 8.6_230]] ) else: raise ValueError(f'''Model name {model_name} not supported.''' ) assert torch.allclose(outputs.logits_per_image , lowerCamelCase , atol=1e-3 ) processor.save_pretrained(lowerCamelCase ) model.save_pretrained(lowerCamelCase ) print('Successfully saved processor and model to' , lowerCamelCase ) if push_to_hub: print('Pushing to the hub...' ) processor.push_to_hub(lowerCamelCase , organization='nielsr' ) model.push_to_hub(lowerCamelCase , organization='nielsr' ) if __name__ == "__main__": __snake_case =argparse.ArgumentParser() parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to dump the processor and PyTorch model.""" ) parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to GroupViT checkpoint""") parser.add_argument( """--model_name""", default="""groupvit-gccy-fcc""", type=str, help="""Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'""", ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.""", ) __snake_case =parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
513
'''simple docstring''' def a_ ( lowerCamelCase : Tuple , lowerCamelCase : Tuple ): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) lowerCAmelCase = (boundary[1] - boundary[0]) / steps lowerCAmelCase = boundary[0] lowerCAmelCase = boundary[1] lowerCAmelCase = make_points(lowerCamelCase , lowerCamelCase , lowerCamelCase ) lowerCAmelCase = 0.0 y += (h / 2.0) * f(lowerCamelCase ) for i in x_i: # print(i) y += h * f(lowerCamelCase ) y += (h / 2.0) * f(lowerCamelCase ) return y def a_ ( lowerCamelCase : Dict , lowerCamelCase : Union[str, Any] , lowerCamelCase : Any ): lowerCAmelCase = a + h while x < (b - h): yield x lowerCAmelCase = x + h def a_ ( lowerCamelCase : Optional[Any] ): # enter your function here lowerCAmelCase = (x - 0) * (x - 0) return y def a_ ( ): lowerCAmelCase = 0.0 # Lower bound of integration lowerCAmelCase = 1.0 # Upper bound of integration lowerCAmelCase = 10.0 # define number of steps or resolution lowerCAmelCase = [a, b] # define boundary of integration lowerCAmelCase = method_a(lowerCamelCase , lowerCamelCase ) print(f'''y = {y}''' ) if __name__ == "__main__": main()
513
1
"""simple docstring""" SCREAMING_SNAKE_CASE_ = 256 # Modulus to hash a string SCREAMING_SNAKE_CASE_ = 1_000_003 def lowercase (_lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = len(_lowerCAmelCase ) __lowerCAmelCase = len(_lowerCAmelCase ) if p_len > t_len: return False __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = 1 # Calculating the hash of pattern and substring of text for i in range(_lowerCAmelCase ): __lowerCAmelCase = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus __lowerCAmelCase = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue __lowerCAmelCase = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash __lowerCAmelCase = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def lowercase (): __lowerCAmelCase = """abc1abc12""" __lowerCAmelCase = """alskfjaldsabc1abc1abc12k23adsfabcabc""" __lowerCAmelCase = """alskfjaldsk23adsfabcabc""" assert rabin_karp(_lowerCAmelCase , _lowerCAmelCase ) and not rabin_karp(_lowerCAmelCase , _lowerCAmelCase ) # Test 2) __lowerCAmelCase = """ABABX""" __lowerCAmelCase = """ABABZABABYABABX""" assert rabin_karp(_lowerCAmelCase , _lowerCAmelCase ) # Test 3) __lowerCAmelCase = """AAAB""" __lowerCAmelCase = """ABAAAAAB""" assert rabin_karp(_lowerCAmelCase , _lowerCAmelCase ) # Test 4) __lowerCAmelCase = """abcdabcy""" __lowerCAmelCase = """abcxabcdabxabcdabcdabcy""" assert rabin_karp(_lowerCAmelCase , _lowerCAmelCase ) # Test 5) __lowerCAmelCase = """Lü""" __lowerCAmelCase = """Lüsai""" assert rabin_karp(_lowerCAmelCase , _lowerCAmelCase ) __lowerCAmelCase = """Lue""" assert not rabin_karp(_lowerCAmelCase , _lowerCAmelCase ) print("""Success.""" ) if __name__ == "__main__": test_rabin_karp()
465
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) class lowerCAmelCase_ ( enum.Enum ): '''simple docstring''' _snake_case = 0 _snake_case = 1 @add_end_docstrings(A__ ) class lowerCAmelCase_ ( A__ ): '''simple docstring''' _snake_case = '''generated''' def __init__( self , *snake_case_ , **snake_case_ ) -> Optional[int]: super().__init__(*snake_case_ , **snake_case_ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def A__ ( self , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , **snake_case_ , ) -> Union[str, Any]: __lowerCAmelCase = {} if truncation is not None: __lowerCAmelCase = truncation __lowerCAmelCase = generate_kwargs __lowerCAmelCase = {} if return_tensors is not None and return_type is None: __lowerCAmelCase = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __lowerCAmelCase = return_type if clean_up_tokenization_spaces is not None: __lowerCAmelCase = clean_up_tokenization_spaces if stop_sequence is not None: __lowerCAmelCase = self.tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) if len(snake_case_ ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) __lowerCAmelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def A__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> Any: return True def A__ ( self , *snake_case_ , snake_case_ ) -> Dict: __lowerCAmelCase = self.model.config.prefix if self.model.config.prefix is not None else """""" if isinstance(args[0] , snake_case_ ): if self.tokenizer.pad_token_id is None: raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input""" ) __lowerCAmelCase = ([prefix + arg for arg in args[0]],) __lowerCAmelCase = True elif isinstance(args[0] , snake_case_ ): __lowerCAmelCase = (prefix + args[0],) __lowerCAmelCase = False else: raise ValueError( f""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __lowerCAmelCase = self.tokenizer(*snake_case_ , padding=snake_case_ , truncation=snake_case_ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self , *snake_case_ , **snake_case_ ) -> Dict: __lowerCAmelCase = super().__call__(*snake_case_ , **snake_case_ ) if ( isinstance(args[0] , snake_case_ ) and all(isinstance(snake_case_ , snake_case_ ) for el in args[0] ) and all(len(snake_case_ ) == 1 for res in result ) ): return [res[0] for res in result] return result def A__ ( self , snake_case_ , snake_case_=TruncationStrategy.DO_NOT_TRUNCATE , **snake_case_ ) -> Tuple: __lowerCAmelCase = self._parse_and_tokenize(snake_case_ , truncation=snake_case_ , **snake_case_ ) return inputs def A__ ( self , snake_case_ , **snake_case_ ) -> Union[str, Any]: if self.framework == "pt": __lowerCAmelCase , __lowerCAmelCase = model_inputs["""input_ids"""].shape elif self.framework == "tf": __lowerCAmelCase , __lowerCAmelCase = tf.shape(model_inputs["""input_ids"""] ).numpy() __lowerCAmelCase = generate_kwargs.get("""min_length""" , self.model.config.min_length ) __lowerCAmelCase = generate_kwargs.get("""max_length""" , self.model.config.max_length ) self.check_inputs(snake_case_ , generate_kwargs["""min_length"""] , generate_kwargs["""max_length"""] ) __lowerCAmelCase = self.model.generate(**snake_case_ , **snake_case_ ) __lowerCAmelCase = output_ids.shape[0] if self.framework == "pt": __lowerCAmelCase = output_ids.reshape(snake_case_ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __lowerCAmelCase = tf.reshape(snake_case_ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def A__ ( self , snake_case_ , snake_case_=ReturnType.TEXT , snake_case_=False ) -> Dict: __lowerCAmelCase = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __lowerCAmelCase = {f"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __lowerCAmelCase = { f"""{self.return_name}_text""": self.tokenizer.decode( snake_case_ , skip_special_tokens=snake_case_ , clean_up_tokenization_spaces=snake_case_ , ) } records.append(snake_case_ ) return records @add_end_docstrings(A__ ) class lowerCAmelCase_ ( A__ ): '''simple docstring''' _snake_case = '''summary''' def __call__( self , *snake_case_ , **snake_case_ ) -> Tuple: return super().__call__(*snake_case_ , **snake_case_ ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> bool: if max_length < min_length: logger.warning(f"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( f"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ """a summarization task, where outputs shorter than the input are typically wanted, you might """ f"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(A__ ) class lowerCAmelCase_ ( A__ ): '''simple docstring''' _snake_case = '''translation''' def A__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: if input_length > 0.9 * max_length: logger.warning( f"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ """increasing your max_length manually, e.g. translator('...', max_length=400)""" ) return True def A__ ( self , *snake_case_ , snake_case_=TruncationStrategy.DO_NOT_TRUNCATE , snake_case_=None , snake_case_=None ) -> List[Any]: if getattr(self.tokenizer , """_build_translation_inputs""" , snake_case_ ): return self.tokenizer._build_translation_inputs( *snake_case_ , return_tensors=self.framework , truncation=snake_case_ , src_lang=snake_case_ , tgt_lang=snake_case_ ) else: return super()._parse_and_tokenize(*snake_case_ , truncation=snake_case_ ) def A__ ( self , snake_case_=None , snake_case_=None , **snake_case_ ) -> List[Any]: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = super()._sanitize_parameters(**snake_case_ ) if src_lang is not None: __lowerCAmelCase = src_lang if tgt_lang is not None: __lowerCAmelCase = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __lowerCAmelCase = kwargs.get("""task""" , self.task ) __lowerCAmelCase = task.split("""_""" ) if task and len(snake_case_ ) == 4: # translation, XX, to YY __lowerCAmelCase = items[1] __lowerCAmelCase = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self , *snake_case_ , **snake_case_ ) -> List[Any]: return super().__call__(*snake_case_ , **snake_case_ )
465
1
import warnings from ..trainer import Trainer from ..utils import logging UpperCAmelCase_ = logging.get_logger(__name__) class UpperCamelCase_ ( _lowerCamelCase ): def __init__( self , lowerCAmelCase_=None , **lowerCAmelCase_ ) -> Dict: warnings.warn( '`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ' 'instead.' , lowerCAmelCase_ , ) super().__init__(args=lowerCAmelCase_ , **lowerCAmelCase_ )
541
def lowerCamelCase__ ( UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : str ) -> List[Any]: '''simple docstring''' if index == r: for j in range(UpperCamelCase__ ): print(data[j] , end=' ' ) print(' ' ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location _snake_case = arr[i] combination_util(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , index + 1 , UpperCamelCase__ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def lowerCamelCase__ ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] ) -> Tuple: '''simple docstring''' _snake_case = [0] * r # Print all combination using temporary array 'data[]' combination_util(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , 0 , UpperCamelCase__ , 0 ) if __name__ == "__main__": # Driver code to check the function above UpperCAmelCase_ = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
541
1
'''simple docstring''' from functools import lru_cache @lru_cache def __snake_case ( UpperCAmelCase_ : int ): if num < 0: raise ValueError("Number should not be negative." ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
675
from __future__ import annotations class __snake_case : """simple docstring""" def __init__( self , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" __snake_case , __snake_case = text, pattern __snake_case , __snake_case = len(_UpperCamelCase ), len(_UpperCamelCase ) def a ( self , _UpperCamelCase ) -> int: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def a ( self , _UpperCamelCase ) -> int: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def a ( self ) -> list[int]: """simple docstring""" __snake_case = [] for i in range(self.textLen - self.patLen + 1 ): __snake_case = self.mismatch_in_text(_UpperCamelCase ) if mismatch_index == -1: positions.append(_UpperCamelCase ) else: __snake_case = self.match_in_pattern(self.text[mismatch_index] ) __snake_case = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions UpperCamelCase__ = '''ABAABA''' UpperCamelCase__ = '''AB''' UpperCamelCase__ = BoyerMooreSearch(text, pattern) UpperCamelCase__ = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
268
0
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a_ :Union[str, Any] = logging.get_logger(__name__) class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""] def __init__( self : List[str], _snake_case : List[str]="</s>", _snake_case : Union[str, Any]="<unk>", _snake_case : Tuple="<pad>", _snake_case : Optional[int]=1_2_5, _snake_case : Dict=None, **_snake_case : List[Any], ) ->None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: snake_case__ : Union[str, Any] = [F'''<extra_id_{i}>''' for i in range(_snake_case )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens snake_case__ : Tuple = len(set(filter(lambda _snake_case : bool('extra_id' in str(_snake_case ) ), _snake_case ) ) ) if extra_tokens != extra_ids: raise ValueError( F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the' ' extra_ids tokens' ) snake_case__ : Optional[Any] = AddedToken(_snake_case, lstrip=_snake_case, rstrip=_snake_case ) if isinstance(_snake_case, _snake_case ) else pad_token snake_case__ : Dict = AddedToken(_snake_case, lstrip=_snake_case, rstrip=_snake_case ) if isinstance(_snake_case, _snake_case ) else eos_token snake_case__ : Tuple = AddedToken(_snake_case, lstrip=_snake_case, rstrip=_snake_case ) if isinstance(_snake_case, _snake_case ) else unk_token super().__init__( eos_token=_snake_case, unk_token=_snake_case, pad_token=_snake_case, extra_ids=_snake_case, additional_special_tokens=_snake_case, **_snake_case, ) snake_case__ : List[Any] = extra_ids snake_case__ : str = 2**8 # utf is 8 bits # define special tokens dict snake_case__ : Dict[int, str] = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } snake_case__ : List[str] = len(self.special_tokens_encoder ) snake_case__ : Dict = len(_snake_case ) for i, token in enumerate(_snake_case ): snake_case__ : Optional[Any] = self.vocab_size + i - n snake_case__ : Dict[str, int] = {v: k for k, v in self.special_tokens_encoder.items()} @property def lowercase_ ( self : Optional[int] ) ->Tuple: return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def lowercase_ ( self : List[str], _snake_case : List[int], _snake_case : Optional[List[int]] = None, _snake_case : bool = False ) ->List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_snake_case, token_ids_a=_snake_case, already_has_special_tokens=_snake_case ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_snake_case )) + [1] return ([0] * len(_snake_case )) + [1] + ([0] * len(_snake_case )) + [1] def lowercase_ ( self : List[Any], _snake_case : List[int] ) ->List[int]: if len(_snake_case ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def lowercase_ ( self : List[str], _snake_case : List[int], _snake_case : Optional[List[int]] = None ) ->List[int]: snake_case__ : int = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowercase_ ( self : Dict, _snake_case : List[int], _snake_case : Optional[List[int]] = None ) ->List[int]: snake_case__ : str = self._add_eos_if_not_present(_snake_case ) if token_ids_a is None: return token_ids_a else: snake_case__ : Tuple = self._add_eos_if_not_present(_snake_case ) return token_ids_a + token_ids_a def lowercase_ ( self : Union[str, Any], _snake_case : str ) ->List[str]: snake_case__ : int = [chr(_snake_case ) for i in text.encode('utf-8' )] return tokens def lowercase_ ( self : Optional[int], _snake_case : Dict ) ->str: if token in self.special_tokens_encoder: snake_case__ : List[Any] = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: snake_case__ : str = self.added_tokens_encoder[token] elif len(_snake_case ) != 1: snake_case__ : List[str] = self.unk_token_id else: snake_case__ : Optional[int] = ord(_snake_case ) + self._num_special_tokens return token_id def lowercase_ ( self : Dict, _snake_case : str ) ->List[Any]: if index in self.special_tokens_decoder: snake_case__ : int = self.special_tokens_decoder[index] else: snake_case__ : Union[str, Any] = chr(index - self._num_special_tokens ) return token def lowercase_ ( self : List[Any], _snake_case : Tuple ) ->str: snake_case__ : Union[str, Any] = b'' for token in tokens: if token in self.special_tokens_decoder: snake_case__ : Union[str, Any] = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.added_tokens_decoder: snake_case__ : Optional[Any] = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.special_tokens_encoder: snake_case__ : Tuple = token.encode('utf-8' ) elif token in self.added_tokens_encoder: snake_case__ : str = token.encode('utf-8' ) else: snake_case__ : Tuple = bytes([ord(_snake_case )] ) bstring += tok_string snake_case__ : Optional[Any] = bstring.decode('utf-8', errors='ignore' ) return string def lowercase_ ( self : Tuple, _snake_case : str, _snake_case : Optional[str] = None ) ->Tuple[str]: return ()
243
import random def lowercase_ (A : int ): snake_case__ : List[str] = num - 1 snake_case__ : Union[str, Any] = 0 while s % 2 == 0: snake_case__ : Any = s // 2 t += 1 for _ in range(5 ): snake_case__ : List[Any] = random.randrange(2 , num - 1 ) snake_case__ : Tuple = pow(A , A , A ) if v != 1: snake_case__ : str = 0 while v != (num - 1): if i == t - 1: return False else: snake_case__ : Tuple = i + 1 snake_case__ : Optional[int] = (v**2) % num return True def lowercase_ (A : int ): if num < 2: return False snake_case__ : Dict = [ 2, 3, 5, 7, 1_1, 1_3, 1_7, 1_9, 2_3, 2_9, 3_1, 3_7, 4_1, 4_3, 4_7, 5_3, 5_9, 6_1, 6_7, 7_1, 7_3, 7_9, 8_3, 8_9, 9_7, 1_0_1, 1_0_3, 1_0_7, 1_0_9, 1_1_3, 1_2_7, 1_3_1, 1_3_7, 1_3_9, 1_4_9, 1_5_1, 1_5_7, 1_6_3, 1_6_7, 1_7_3, 1_7_9, 1_8_1, 1_9_1, 1_9_3, 1_9_7, 1_9_9, 2_1_1, 2_2_3, 2_2_7, 2_2_9, 2_3_3, 2_3_9, 2_4_1, 2_5_1, 2_5_7, 2_6_3, 2_6_9, 2_7_1, 2_7_7, 2_8_1, 2_8_3, 2_9_3, 3_0_7, 3_1_1, 3_1_3, 3_1_7, 3_3_1, 3_3_7, 3_4_7, 3_4_9, 3_5_3, 3_5_9, 3_6_7, 3_7_3, 3_7_9, 3_8_3, 3_8_9, 3_9_7, 4_0_1, 4_0_9, 4_1_9, 4_2_1, 4_3_1, 4_3_3, 4_3_9, 4_4_3, 4_4_9, 4_5_7, 4_6_1, 4_6_3, 4_6_7, 4_7_9, 4_8_7, 4_9_1, 4_9_9, 5_0_3, 5_0_9, 5_2_1, 5_2_3, 5_4_1, 5_4_7, 5_5_7, 5_6_3, 5_6_9, 5_7_1, 5_7_7, 5_8_7, 5_9_3, 5_9_9, 6_0_1, 6_0_7, 6_1_3, 6_1_7, 6_1_9, 6_3_1, 6_4_1, 6_4_3, 6_4_7, 6_5_3, 6_5_9, 6_6_1, 6_7_3, 6_7_7, 6_8_3, 6_9_1, 7_0_1, 7_0_9, 7_1_9, 7_2_7, 7_3_3, 7_3_9, 7_4_3, 7_5_1, 7_5_7, 7_6_1, 7_6_9, 7_7_3, 7_8_7, 7_9_7, 8_0_9, 8_1_1, 8_2_1, 8_2_3, 8_2_7, 8_2_9, 8_3_9, 8_5_3, 8_5_7, 8_5_9, 8_6_3, 8_7_7, 8_8_1, 8_8_3, 8_8_7, 9_0_7, 9_1_1, 9_1_9, 9_2_9, 9_3_7, 9_4_1, 9_4_7, 9_5_3, 9_6_7, 9_7_1, 9_7_7, 9_8_3, 9_9_1, 9_9_7, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(A ) def lowercase_ (A : int = 1_0_2_4 ): while True: snake_case__ : List[str] = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(A ): return num if __name__ == "__main__": a_ :Any = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
243
1
'''simple docstring''' def lowercase_ ( __A : List[str] ) -> Union[str, Any]: """simple docstring""" lowercase : str =[0] * len(__A ) lowercase : Union[str, Any] =[] lowercase : str =[] lowercase : List[Any] =0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__A ) ): if indegree[i] == 0: queue.append(__A ) while queue: lowercase : List[str] =queue.pop(0 ) cnt += 1 topo.append(__A ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(__A ) if cnt != len(__A ): print('''Cycle exists''' ) else: print(__A ) # Adjacency List of Graph SCREAMING_SNAKE_CASE = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
94
"""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 UpperCamelCase__ ( a_): """simple docstring""" def __init__( self : List[str] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[int]=1_3 , UpperCamelCase_ : Dict=7 , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Optional[int]=True , UpperCamelCase_ : Tuple=False , UpperCamelCase_ : Union[str, Any]=False , UpperCamelCase_ : Any=False , UpperCamelCase_ : Tuple=2 , UpperCamelCase_ : List[Any]=9_9 , UpperCamelCase_ : List[Any]=0 , UpperCamelCase_ : Tuple=3_2 , UpperCamelCase_ : Any=5 , UpperCamelCase_ : Dict=4 , UpperCamelCase_ : Tuple=0.1 , UpperCamelCase_ : Any=0.1 , UpperCamelCase_ : Optional[Any]=5_1_2 , UpperCamelCase_ : Union[str, Any]=1_2 , UpperCamelCase_ : List[str]=2 , UpperCamelCase_ : str=0.02 , UpperCamelCase_ : List[str]=3 , UpperCamelCase_ : Dict=4 , UpperCamelCase_ : Optional[int]="last" , UpperCamelCase_ : List[str]=None , UpperCamelCase_ : Tuple=None , ): '''simple docstring''' __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_lengths __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = gelu_activation __magic_name__ = sinusoidal_embeddings __magic_name__ = causal __magic_name__ = asm __magic_name__ = n_langs __magic_name__ = vocab_size __magic_name__ = n_special __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = summary_type __magic_name__ = use_proj __magic_name__ = scope def a__ ( self : List[str] ): '''simple docstring''' __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_input_lengths: __magic_name__ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , 2 ).float() __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a__ ( self : int ): '''simple docstring''' 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 a__ ( self : Dict , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : str , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[int] , ): '''simple docstring''' __magic_name__ = FlaubertModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() __magic_name__ = model(UpperCamelCase_ , lengths=UpperCamelCase_ , langs=UpperCamelCase_ ) __magic_name__ = model(UpperCamelCase_ , langs=UpperCamelCase_ ) __magic_name__ = model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Any , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Tuple , UpperCamelCase_ : int , UpperCamelCase_ : str , ): '''simple docstring''' __magic_name__ = FlaubertWithLMHeadModel(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() __magic_name__ = model(UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a__ ( self : Union[str, Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[Any] , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : str , ): '''simple docstring''' __magic_name__ = FlaubertForQuestionAnsweringSimple(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() __magic_name__ = model(UpperCamelCase_ ) __magic_name__ = model(UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a__ ( self : str , UpperCamelCase_ : int , UpperCamelCase_ : Any , UpperCamelCase_ : Any , UpperCamelCase_ : Any , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Union[str, Any] , ): '''simple docstring''' __magic_name__ = FlaubertForQuestionAnswering(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() __magic_name__ = model(UpperCamelCase_ ) __magic_name__ = model( UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ , cls_index=UpperCamelCase_ , is_impossible=UpperCamelCase_ , p_mask=UpperCamelCase_ , ) __magic_name__ = model( UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ , cls_index=UpperCamelCase_ , is_impossible=UpperCamelCase_ , ) ((__magic_name__) , ) = result_with_labels.to_tuple() __magic_name__ = model(UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ ) ((__magic_name__) , ) = 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 a__ ( self : str , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[str] , ): '''simple docstring''' __magic_name__ = FlaubertForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() __magic_name__ = model(UpperCamelCase_ ) __magic_name__ = model(UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self : Optional[int] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : str , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Tuple , ): '''simple docstring''' __magic_name__ = self.num_labels __magic_name__ = FlaubertForTokenClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() __magic_name__ = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a__ ( self : str , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple , ): '''simple docstring''' __magic_name__ = self.num_choices __magic_name__ = FlaubertForMultipleChoice(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a__ ( self : Union[str, Any] ): '''simple docstring''' __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class UpperCamelCase__ ( a_ , a_ , unittest.TestCase): """simple docstring""" __UpperCAmelCase = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) __UpperCAmelCase = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def a__ ( self : List[str] , UpperCamelCase_ : Any , UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Dict ): '''simple docstring''' 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 a__ ( self : List[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[Any]=False ): '''simple docstring''' __magic_name__ = super()._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": __magic_name__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase_ ) __magic_name__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase_ ) return inputs_dict def a__ ( self : List[str] ): '''simple docstring''' __magic_name__ = FlaubertModelTester(self ) __magic_name__ = ConfigTester(self , config_class=UpperCamelCase_ , emb_dim=3_7 ) def a__ ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() def a__ ( self : Optional[Any] ): '''simple docstring''' __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*UpperCamelCase_ ) def a__ ( self : Dict ): '''simple docstring''' __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*UpperCamelCase_ ) def a__ ( self : int ): '''simple docstring''' __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*UpperCamelCase_ ) def a__ ( self : int ): '''simple docstring''' __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*UpperCamelCase_ ) def a__ ( self : Optional[int] ): '''simple docstring''' __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCamelCase_ ) def a__ ( self : str ): '''simple docstring''' __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*UpperCamelCase_ ) def a__ ( self : Union[str, Any] ): '''simple docstring''' __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*UpperCamelCase_ ) @slow def a__ ( self : Any ): '''simple docstring''' for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ = FlaubertModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @slow @require_torch_gpu def a__ ( self : str ): '''simple docstring''' __magic_name__ , __magic_name__ = 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 __magic_name__ = True __magic_name__ = model_class(config=UpperCamelCase_ ) __magic_name__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) __magic_name__ = torch.jit.trace( UpperCamelCase_ , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCamelCase_ , os.path.join(UpperCamelCase_ , 'traced_model.pt' ) ) __magic_name__ = torch.jit.load(os.path.join(UpperCamelCase_ , 'traced_model.pt' ) , map_location=UpperCamelCase_ ) loaded(inputs_dict['input_ids'].to(UpperCamelCase_ ) , inputs_dict['attention_mask'].to(UpperCamelCase_ ) ) @require_torch class UpperCamelCase__ ( unittest.TestCase): """simple docstring""" @slow def a__ ( self : Dict ): '''simple docstring''' __magic_name__ = FlaubertModel.from_pretrained('flaubert/flaubert_base_cased' ) __magic_name__ = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) with torch.no_grad(): __magic_name__ = model(UpperCamelCase_ )[0] __magic_name__ = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , UpperCamelCase_ ) __magic_name__ = torch.tensor( [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase_ , atol=1e-4 ) )
545
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class _UpperCamelCase ( _UpperCAmelCase ): """simple docstring""" __a : torch.FloatTensor class _UpperCamelCase ( _UpperCAmelCase ,_UpperCAmelCase ): """simple docstring""" @register_to_config def __init__( self , lowerCAmelCase__ = 3 , lowerCAmelCase__ = 3 , lowerCAmelCase__ = ("DownEncoderBlock2D",) , lowerCAmelCase__ = ("UpDecoderBlock2D",) , lowerCAmelCase__ = (64,) , lowerCAmelCase__ = 1 , lowerCAmelCase__ = "silu" , lowerCAmelCase__ = 3 , lowerCAmelCase__ = 32 , lowerCAmelCase__ = 2_56 , lowerCAmelCase__ = 32 , lowerCAmelCase__ = None , lowerCAmelCase__ = 0.1_8215 , lowerCAmelCase__ = "group" , ) -> Tuple: '''simple docstring''' super().__init__() # pass init params to Encoder __lowercase = Encoder( in_channels=lowerCAmelCase__ , out_channels=lowerCAmelCase__ , down_block_types=lowerCAmelCase__ , block_out_channels=lowerCAmelCase__ , layers_per_block=lowerCAmelCase__ , act_fn=lowerCAmelCase__ , norm_num_groups=lowerCAmelCase__ , double_z=lowerCAmelCase__ , ) __lowercase = vq_embed_dim if vq_embed_dim is not None else latent_channels __lowercase = nn.Convad(lowerCAmelCase__ , lowerCAmelCase__ , 1 ) __lowercase = VectorQuantizer(lowerCAmelCase__ , lowerCAmelCase__ , beta=0.25 , remap=lowerCAmelCase__ , sane_index_shape=lowerCAmelCase__ ) __lowercase = nn.Convad(lowerCAmelCase__ , lowerCAmelCase__ , 1 ) # pass init params to Decoder __lowercase = Decoder( in_channels=lowerCAmelCase__ , out_channels=lowerCAmelCase__ , up_block_types=lowerCAmelCase__ , block_out_channels=lowerCAmelCase__ , layers_per_block=lowerCAmelCase__ , act_fn=lowerCAmelCase__ , norm_num_groups=lowerCAmelCase__ , norm_type=lowerCAmelCase__ , ) @apply_forward_hook def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ = True ) -> VQEncoderOutput: '''simple docstring''' __lowercase = self.encoder(lowerCAmelCase__ ) __lowercase = self.quant_conv(lowerCAmelCase__ ) if not return_dict: return (h,) return VQEncoderOutput(latents=lowerCAmelCase__ ) @apply_forward_hook def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' if not force_not_quantize: __lowercase , __lowercase , __lowercase = self.quantize(lowerCAmelCase__ ) else: __lowercase = h __lowercase = self.post_quant_conv(lowerCAmelCase__ ) __lowercase = self.decoder(lowerCAmelCase__ , quant if self.config.norm_type == '''spatial''' else None ) if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' __lowercase = sample __lowercase = self.encode(lowerCAmelCase__ ).latents __lowercase = self.decode(lowerCAmelCase__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase__ )
522
import random from typing import Any def UpperCAmelCase ( lowercase ): """simple docstring""" for _ in range(len(lowercase ) ): __lowercase = random.randint(0 , len(lowercase ) - 1 ) __lowercase = random.randint(0 , len(lowercase ) - 1 ) __lowercase , __lowercase = data[b], data[a] return data if __name__ == "__main__": __a : List[str] = [0, 1, 2, 3, 4, 5, 6, 7] __a : Any = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
522
1
"""simple docstring""" import numpy as np def lowercase__ ( lowerCAmelCase__ : Union[str, Any] ) -> Dict: '''simple docstring''' return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
642
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): """simple docstring""" # Initialise PyTorch model _lowerCAmelCase = BigBirdConfig.from_json_file(__lowerCamelCase ) print(F'''Building PyTorch model from configuration: {config}''' ) if is_trivia_qa: _lowerCAmelCase = BigBirdForQuestionAnswering(__lowerCamelCase ) else: _lowerCAmelCase = BigBirdForPreTraining(__lowerCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__lowerCamelCase, __lowerCamelCase, is_trivia_qa=__lowerCamelCase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": a__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--big_bird_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--is_trivia_qa""", action="""store_true""", help="""Whether to convert a model with a trivia_qa head.""" ) a__ : List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
589
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase_ ( __magic_name__ ,__magic_name__ ): __lowerCamelCase : str = "nat" __lowerCamelCase : Union[str, Any] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , _lowerCAmelCase=4 , _lowerCAmelCase=3 , _lowerCAmelCase=64 , _lowerCAmelCase=[3, 4, 6, 5] , _lowerCAmelCase=[2, 4, 8, 16] , _lowerCAmelCase=7 , _lowerCAmelCase=3.0 , _lowerCAmelCase=True , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.1 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-5 , _lowerCAmelCase=0.0 , _lowerCAmelCase=None , _lowerCAmelCase=None , **_lowerCAmelCase , ) -> Union[str, Any]: super().__init__(**_lowerCAmelCase ) _lowerCAmelCase = patch_size _lowerCAmelCase = num_channels _lowerCAmelCase = embed_dim _lowerCAmelCase = depths _lowerCAmelCase = len(_lowerCAmelCase ) _lowerCAmelCase = num_heads _lowerCAmelCase = kernel_size _lowerCAmelCase = mlp_ratio _lowerCAmelCase = qkv_bias _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = drop_path_rate _lowerCAmelCase = hidden_act _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _lowerCAmelCase = int(embed_dim * 2 ** (len(_lowerCAmelCase ) - 1) ) _lowerCAmelCase = layer_scale_init_value _lowerCAmelCase = ["stem"] + [f'''stage{idx}''' for idx in range(1 , len(_lowerCAmelCase ) + 1 )] _lowerCAmelCase , _lowerCAmelCase = get_aligned_output_features_output_indices( out_features=_lowerCAmelCase , out_indices=_lowerCAmelCase , stage_names=self.stage_names )
489
'''simple docstring''' _SCREAMING_SNAKE_CASE = range(2, 20 + 1) _SCREAMING_SNAKE_CASE = [10**k for k in range(ks[-1] + 1)] _SCREAMING_SNAKE_CASE = {} def __a(SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): '''simple docstring''' _lowerCAmelCase = sum(a_i[j] for j in range(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ) ) _lowerCAmelCase = sum(a_i[j] * base[j] for j in range(min(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) ) _lowerCAmelCase , _lowerCAmelCase = 0, 0 _lowerCAmelCase = n - i _lowerCAmelCase = memo.get(SCREAMING_SNAKE_CASE_ ) if sub_memo is not None: _lowerCAmelCase = sub_memo.get(SCREAMING_SNAKE_CASE_ ) if jumps is not None and len(SCREAMING_SNAKE_CASE_ ) > 0: # find and make the largest jump without going over _lowerCAmelCase = -1 for _k in range(len(SCREAMING_SNAKE_CASE_ ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: _lowerCAmelCase = _k break if max_jump >= 0: _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = jumps[max_jump] # since the difference between jumps is cached, add c _lowerCAmelCase = diff + c for j in range(min(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ) ): _lowerCAmelCase , _lowerCAmelCase = divmod(SCREAMING_SNAKE_CASE_ , 10 ) if new_c > 0: add(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: _lowerCAmelCase = [] else: _lowerCAmelCase = {c: []} _lowerCAmelCase = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _lowerCAmelCase , _lowerCAmelCase = next_term(SCREAMING_SNAKE_CASE_ , k - 1 , i + dn , SCREAMING_SNAKE_CASE_ ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _lowerCAmelCase , _lowerCAmelCase = compute(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , i + dn , SCREAMING_SNAKE_CASE_ ) diff += _diff dn += terms_jumped _lowerCAmelCase = sub_memo[c] # keep jumps sorted by # of terms skipped _lowerCAmelCase = 0 while j < len(SCREAMING_SNAKE_CASE_ ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(SCREAMING_SNAKE_CASE_ , (diff, dn, k) ) return (diff, dn) def __a(SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): '''simple docstring''' if i >= n: return 0, i if k > len(SCREAMING_SNAKE_CASE_ ): a_i.extend([0 for _ in range(k - len(SCREAMING_SNAKE_CASE_ ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) _lowerCAmelCase = i _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 0, 0, 0 for j in range(len(SCREAMING_SNAKE_CASE_ ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 _lowerCAmelCase = ds_c + ds_b diff += addend _lowerCAmelCase = 0 for j in range(SCREAMING_SNAKE_CASE_ ): _lowerCAmelCase = a_i[j] + addend _lowerCAmelCase , _lowerCAmelCase = divmod(SCREAMING_SNAKE_CASE_ , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return diff, i - start_i def __a(SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any ): '''simple docstring''' for j in range(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ): _lowerCAmelCase = digits[j] + addend if s >= 10: _lowerCAmelCase , _lowerCAmelCase = divmod(SCREAMING_SNAKE_CASE_ , 10 ) _lowerCAmelCase = addend // 10 + quotient else: _lowerCAmelCase = s _lowerCAmelCase = addend // 10 if addend == 0: break while addend > 0: _lowerCAmelCase , _lowerCAmelCase = divmod(SCREAMING_SNAKE_CASE_ , 10 ) digits.append(SCREAMING_SNAKE_CASE_ ) def __a(SCREAMING_SNAKE_CASE_ : int = 10**15 ): '''simple docstring''' _lowerCAmelCase = [1] _lowerCAmelCase = 1 _lowerCAmelCase = 0 while True: _lowerCAmelCase , _lowerCAmelCase = next_term(SCREAMING_SNAKE_CASE_ , 20 , i + dn , SCREAMING_SNAKE_CASE_ ) dn += terms_jumped if dn == n - i: break _lowerCAmelCase = 0 for j in range(len(SCREAMING_SNAKE_CASE_ ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f'''{solution() = }''')
489
1
"""simple docstring""" import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( 'The `image_to_image.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionImg2ImgPipeline` instead.' )
621
"""simple docstring""" def lowercase__ ( lowerCamelCase, lowerCamelCase ): return abs(lowerCamelCase ) if a == 0 else greatest_common_divisor(b % a, lowerCamelCase ) def lowercase__ ( lowerCamelCase, lowerCamelCase ): while y: # --> when y=0 then loop will terminate and return x as final GCD. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = y, x % y return abs(lowerCamelCase ) def lowercase__ ( ): try: _SCREAMING_SNAKE_CASE : Union[str, Any] = input('Enter two integers separated by comma (,): ' ).split(',' ) _SCREAMING_SNAKE_CASE : Dict = int(nums[0] ) _SCREAMING_SNAKE_CASE : Dict = int(nums[1] ) print( f"""greatest_common_divisor({num_a}, {num_a}) = """ f"""{greatest_common_divisor(lowerCamelCase, lowerCamelCase )}""" ) print(f"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(lowerCamelCase, lowerCamelCase )}""" ) except (IndexError, UnboundLocalError, ValueError): print('Wrong input' ) if __name__ == "__main__": main()
621
1
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class A__ ( unittest.TestCase): """simple docstring""" def a__ ( self: Union[str, Any] )-> Optional[int]: lowerCamelCase : Union[str, Any] = inspect.getfile(accelerate.test_utils ) lowerCamelCase : List[Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps""", """test_metrics.py"""] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowerCamelCase : Dict = test_metrics @require_cpu def a__ ( self: Tuple )-> Optional[int]: debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def a__ ( self: int )-> List[str]: debug_launcher(self.test_metrics.main ) @require_single_gpu def a__ ( self: Dict )-> Dict: self.test_metrics.main() @require_multi_gpu def a__ ( self: str )-> str: print(f'Found {torch.cuda.device_count()} devices.' ) lowerCamelCase : Optional[int] = ["""torchrun""", f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() )
42
"""simple docstring""" import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils import require_multi_gpu class A__ ( nn.Module): """simple docstring""" def __init__( self: Dict )-> Dict: super().__init__() lowerCamelCase : Tuple = nn.Linear(3 , 4 ) lowerCamelCase : Optional[Any] = nn.BatchNormad(4 ) lowerCamelCase : Optional[Any] = nn.Linear(4 , 5 ) def a__ ( self: List[str] , __a: List[Any] )-> Optional[Any]: return self.lineara(self.batchnorm(self.lineara(__a ) ) ) class A__ ( __lowercase): """simple docstring""" def a__ ( self: Tuple , __a: int , *__a: Any , **__a: Tuple )-> Tuple: return (args[0] + 1,) + args[1:], kwargs class A__ ( __lowercase): """simple docstring""" def a__ ( self: Optional[int] , __a: List[str] , __a: List[Any] )-> List[str]: return output + 1 class A__ ( unittest.TestCase): """simple docstring""" def a__ ( self: int )-> str: lowerCamelCase : List[str] = ModelForTest() lowerCamelCase : Dict = ModelHook() add_hook_to_module(__a , __a ) self.assertEqual(test_model._hf_hook , __a ) self.assertTrue(hasattr(__a , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__a ) self.assertFalse(hasattr(__a , """_hf_hook""" ) ) self.assertFalse(hasattr(__a , """_old_forward""" ) ) def a__ ( self: int )-> str: lowerCamelCase : List[str] = ModelForTest() lowerCamelCase : Union[str, Any] = ModelHook() add_hook_to_module(__a , __a ) add_hook_to_module(__a , __a , append=__a ) self.assertEqual(isinstance(test_model._hf_hook , __a ) , __a ) self.assertEqual(len(test_model._hf_hook.hooks ) , 2 ) self.assertTrue(hasattr(__a , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__a ) self.assertFalse(hasattr(__a , """_hf_hook""" ) ) self.assertFalse(hasattr(__a , """_old_forward""" ) ) def a__ ( self: List[Any] )-> List[str]: lowerCamelCase : str = ModelForTest() lowerCamelCase : Dict = torch.randn(2 , 3 ) lowerCamelCase : Union[str, Any] = test_model(x + 1 ) lowerCamelCase : Optional[int] = test_model(x + 2 ) lowerCamelCase : List[Any] = PreForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Optional[int] = test_model(__a ) self.assertTrue(torch.allclose(__a , __a , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain lowerCamelCase : Dict = PreForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Tuple = test_model(__a ) self.assertTrue(torch.allclose(__a , __a , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks lowerCamelCase : Any = SequentialHook(PreForwardHook() , PreForwardHook() ) add_hook_to_module(__a , __a ) lowerCamelCase : Optional[Any] = test_model(__a ) assert torch.allclose(__a , __a , atol=1e-5 ) def a__ ( self: Any )-> Optional[int]: lowerCamelCase : str = ModelForTest() lowerCamelCase : List[str] = torch.randn(2 , 3 ) lowerCamelCase : int = test_model(__a ) lowerCamelCase : Dict = PostForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Tuple = test_model(__a ) self.assertTrue(torch.allclose(__a , output + 1 , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain lowerCamelCase : str = PostForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Optional[Any] = test_model(__a ) self.assertTrue(torch.allclose(__a , output + 1 , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks lowerCamelCase : Union[str, Any] = SequentialHook(PostForwardHook() , PostForwardHook() ) add_hook_to_module(__a , __a ) lowerCamelCase : str = test_model(__a ) assert torch.allclose(__a , output + 2 , atol=1e-5 ) def a__ ( self: int )-> Dict: lowerCamelCase : List[Any] = ModelForTest() lowerCamelCase : Optional[int] = torch.randn(2 , 3 ) lowerCamelCase : List[str] = test_model(__a ) lowerCamelCase : Any = PostForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : str = test_model(__a ) self.assertTrue(torch.allclose(__a , output + 1 ) ) self.assertTrue(outputa.requires_grad ) lowerCamelCase : Optional[int] = True lowerCamelCase : Optional[int] = test_model(__a ) self.assertFalse(outputa.requires_grad ) @require_multi_gpu def a__ ( self: List[str] )-> Union[str, Any]: lowerCamelCase : int = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=1 ) ) self.assertEqual(model.lineara.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device(0 ) ) self.assertEqual(model.lineara.weight.device , torch.device(1 ) ) # We can still make a forward pass. The input does not need to be on any particular device lowerCamelCase : str = torch.randn(2 , 3 ) lowerCamelCase : Dict = model(__a ) self.assertEqual(output.device , torch.device(1 ) ) # We can add a general hook to put back output on same device as input. add_hook_to_module(__a , AlignDevicesHook(io_same_device=__a ) ) lowerCamelCase : Optional[int] = torch.randn(2 , 3 ).to(0 ) lowerCamelCase : str = model(__a ) self.assertEqual(output.device , torch.device(0 ) ) def a__ ( self: List[str] )-> Tuple: lowerCamelCase : Union[str, Any] = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices lowerCamelCase : Tuple = {"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True} add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__a ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device lowerCamelCase : List[Any] = torch.device(hook_kwargs["""execution_device"""] ) self.assertEqual(model.batchnorm.running_mean.device , __a ) lowerCamelCase : Optional[Any] = torch.randn(2 , 3 ) lowerCamelCase : Optional[Any] = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload lowerCamelCase : Any = { """execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True, """offload_buffers""": True, } add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__a ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) lowerCamelCase : int = torch.randn(2 , 3 ) lowerCamelCase : Optional[int] = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def a__ ( self: Any )-> List[str]: lowerCamelCase : int = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices lowerCamelCase : int = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook(__a , execution_device=__a , offload=__a ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device lowerCamelCase : List[Any] = torch.device(__a ) self.assertEqual(model.batchnorm.running_mean.device , __a ) lowerCamelCase : Dict = torch.randn(2 , 3 ) lowerCamelCase : Optional[Any] = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook(__a , execution_device=__a , offload=__a , offload_buffers=__a ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) lowerCamelCase : Optional[int] = torch.randn(2 , 3 ) lowerCamelCase : int = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def a__ ( self: Optional[Any] )-> List[Any]: lowerCamelCase : List[Any] = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices lowerCamelCase : Any = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook( __a , execution_device=__a , offload=__a , weights_map=model.state_dict() ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device lowerCamelCase : List[Any] = torch.device(__a ) self.assertEqual(model.batchnorm.running_mean.device , __a ) lowerCamelCase : Dict = torch.randn(2 , 3 ) lowerCamelCase : int = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook( __a , execution_device=__a , offload=__a , weights_map=model.state_dict() , offload_buffers=__a , ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) lowerCamelCase : Tuple = torch.randn(2 , 3 ) lowerCamelCase : Any = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) )
42
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : List[Any] = logging.get_logger(__name__) a__ : str = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''ctrl''' __SCREAMING_SNAKE_CASE = ['''past_key_values'''] __SCREAMING_SNAKE_CASE = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , lowercase=2_4_6_5_3_4 , lowercase=2_5_6 , lowercase=1_2_8_0 , lowercase=8_1_9_2 , lowercase=4_8 , lowercase=1_6 , lowercase=0.1 , lowercase=0.1 , lowercase=1E-6 , lowercase=0.02 , lowercase=True , **lowercase , ) -> Any: __UpperCamelCase = vocab_size __UpperCamelCase = n_positions __UpperCamelCase = n_embd __UpperCamelCase = n_layer __UpperCamelCase = n_head __UpperCamelCase = dff __UpperCamelCase = resid_pdrop __UpperCamelCase = embd_pdrop __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = initializer_range __UpperCamelCase = use_cache super().__init__(**lowercase )
601
'''simple docstring''' import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self , lowercase ) -> str: for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): __UpperCamelCase = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(lowercase ) def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = """sgugger/tiny-distilbert-classification""" __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , only_pretrain_model=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , torchscript=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , fpaa=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = AutoConfig.from_pretrained(lowercase ) # set architectures equal to `None` __UpperCamelCase = None __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase , configs=[config] ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=lowercase , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = AutoConfig.from_pretrained(lowercase ) __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase , configs=[config] ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = """sshleifer/tinier_bart""" __UpperCamelCase = AutoConfig.from_pretrained(lowercase ) __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase , configs=[config] ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = """sshleifer/tiny-gpt2""" __UpperCamelCase = AutoConfig.from_pretrained(lowercase ) __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase , configs=[config] ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = """sshleifer/tinier_bart""" __UpperCamelCase = AutoConfig.from_pretrained(lowercase ) __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase , configs=[config] ) __UpperCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , save_to_csv=lowercase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(lowercase , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(lowercase , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(lowercase , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(lowercase , """train_time.csv""" ) , env_info_csv_file=os.path.join(lowercase , """env.csv""" ) , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) benchmark.run() self.assertTrue(Path(os.path.join(lowercase , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(lowercase , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(lowercase , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(lowercase , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(lowercase , """env.csv""" ) ).exists() ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(lowercase ): self.assertTrue(hasattr(lowercase , """sequential""" ) ) self.assertTrue(hasattr(lowercase , """cumulative""" ) ) self.assertTrue(hasattr(lowercase , """current""" ) ) self.assertTrue(hasattr(lowercase , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: __UpperCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=lowercase , inference=lowercase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(lowercase , """log.txt""" ) , log_print=lowercase , trace_memory_line_by_line=lowercase , multi_process=lowercase , ) __UpperCamelCase = PyTorchBenchmark(lowercase ) __UpperCamelCase = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(lowercase , """log.txt""" ) ).exists() )
601
1
"""simple docstring""" from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __lowercase ( a : int ) -> int: __snake_case : Optional[int] =prime_factors(a ) if is_square_free(a ): return -1 if len(a ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
715
"""simple docstring""" from __future__ import annotations def __lowercase ( a : int , a : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __snake_case : List[str] =number_of_bytes // partitions __snake_case : str =[] for i in range(a ): __snake_case : Optional[Any] =i * bytes_per_partition + 1 __snake_case : Any =( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
497
0
def UpperCamelCase ( lowercase_ ) -> list: '''simple docstring''' for i in range(len(lowercase_ ) - 1 , 0 , -1 ): lowercase__ : Union[str, Any] = False for j in range(lowercase_ , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: lowercase__ , lowercase__ : Tuple = unsorted[j - 1], unsorted[j] lowercase__ : str = True for j in range(lowercase_ ): if unsorted[j] > unsorted[j + 1]: lowercase__ , lowercase__ : List[Any] = unsorted[j + 1], unsorted[j] lowercase__ : Dict = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ : Optional[int] = input("""Enter numbers separated by a comma:\n""").strip() lowerCamelCase__ : Dict = [int(item) for item in user_input.split(""",""")] print(f'''{cocktail_shaker_sort(unsorted) = }''')
12
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING lowercase_ = logging.get_logger(__name__) lowercase_ = { "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = 'blip_2_vision_model' def __init__( self , _a=1_408 , _a=6_144 , _a=39 , _a=16 , _a=224 , _a=14 , _a="gelu" , _a=0.0_0001 , _a=0.0 , _a=1E-10 , _a=True , **_a , ): super().__init__(**_a ) __a = hidden_size __a = intermediate_size __a = num_hidden_layers __a = num_attention_heads __a = patch_size __a = image_size __a = initializer_range __a = attention_dropout __a = layer_norm_eps __a = hidden_act __a = qkv_bias @classmethod def __UpperCAmelCase ( cls , _a , **_a ): cls._set_token_in_kwargs(_a ) __a , __a = cls.get_config_dict(_a , **_a ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": __a = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_a , **_a ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 'blip_2_qformer' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=0.02 , _a=1E-12 , _a=0 , _a="absolute" , _a=2 , _a=1_408 , **_a , ): super().__init__(pad_token_id=_a , **_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = cross_attention_frequency __a = encoder_hidden_size @classmethod def __UpperCAmelCase ( cls , _a , **_a ): cls._set_token_in_kwargs(_a ) __a , __a = cls.get_config_dict(_a , **_a ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": __a = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_a , **_a ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = 'blip-2' __UpperCAmelCase : List[str] = True def __init__( self , _a=None , _a=None , _a=None , _a=32 , **_a ): super().__init__(**_a ) if vision_config is None: __a = {} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: __a = {} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: __a = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) __a = BlipaVisionConfig(**_a ) __a = BlipaQFormerConfig(**_a ) __a = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' __a = CONFIG_MAPPING[text_model_type](**_a ) __a = self.text_config.tie_word_embeddings __a = self.text_config.is_encoder_decoder __a = num_query_tokens __a = self.vision_config.hidden_size __a = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __a = 1.0 __a = 0.02 @classmethod def __UpperCAmelCase ( cls , _a , _a , _a , **_a , ): return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_a , ) def __UpperCAmelCase ( self ): __a = copy.deepcopy(self.__dict__ ) __a = self.vision_config.to_dict() __a = self.qformer_config.to_dict() __a = self.text_config.to_dict() __a = self.__class__.model_type return output
695
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _lowerCAmelCase ( __a , unittest.TestCase ): _lowercase =KandinskyInpaintPipeline _lowercase =['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image'''] _lowercase =[ '''prompt''', '''negative_prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''', ] _lowercase =[ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''negative_prompt''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] _lowercase =False @property def __a ( self ) -> List[Any]: return 32 @property def __a ( self ) -> str: return 32 @property def __a ( self ) -> List[str]: return self.time_input_dim @property def __a ( self ) -> Any: return self.time_input_dim * 4 @property def __a ( self ) -> Union[str, Any]: return 100 @property def __a ( self ) -> Dict: lowerCAmelCase_ = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __a ( self ) -> Optional[Any]: torch.manual_seed(0 ) lowerCAmelCase_ = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_005 , ) lowerCAmelCase_ = MultilingualCLIP(_UpperCamelCase ) lowerCAmelCase_ = text_encoder.eval() return text_encoder @property def __a ( self ) -> str: torch.manual_seed(0 ) lowerCAmelCase_ = { "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_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": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } lowerCAmelCase_ = UNetaDConditionModel(**_UpperCamelCase ) return model @property def __a ( self ) -> List[Any]: 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 __a ( self ) -> Tuple: torch.manual_seed(0 ) lowerCAmelCase_ = VQModel(**self.dummy_movq_kwargs ) return model def __a ( self ) -> Tuple: lowerCAmelCase_ = self.dummy_text_encoder lowerCAmelCase_ = self.dummy_tokenizer lowerCAmelCase_ = self.dummy_unet lowerCAmelCase_ = self.dummy_movq lowerCAmelCase_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="linear" , beta_start=0.00085 , beta_end=0.012 , clip_sample=_UpperCamelCase , set_alpha_to_one=_UpperCamelCase , steps_offset=1 , prediction_type="epsilon" , thresholding=_UpperCamelCase , ) lowerCAmelCase_ = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __a ( self , _UpperCamelCase , _UpperCamelCase=0 ) -> Any: lowerCAmelCase_ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_UpperCamelCase ) ).to(_UpperCamelCase ) lowerCAmelCase_ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_UpperCamelCase ) # create init_image lowerCAmelCase_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(_UpperCamelCase ) ).to(_UpperCamelCase ) lowerCAmelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCAmelCase_ = Image.fromarray(np.uinta(_UpperCamelCase ) ).convert("RGB" ).resize((256, 256) ) # create mask lowerCAmelCase_ = np.ones((64, 64) , dtype=np.floataa ) lowerCAmelCase_ = 0 if str(_UpperCamelCase ).startswith("mps" ): lowerCAmelCase_ = torch.manual_seed(_UpperCamelCase ) else: lowerCAmelCase_ = torch.Generator(device=_UpperCamelCase ).manual_seed(_UpperCamelCase ) lowerCAmelCase_ = { "prompt": "horse", "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def __a ( self ) -> List[Any]: lowerCAmelCase_ = "cpu" lowerCAmelCase_ = self.get_dummy_components() lowerCAmelCase_ = self.pipeline_class(**_UpperCamelCase ) lowerCAmelCase_ = pipe.to(_UpperCamelCase ) pipe.set_progress_bar_config(disable=_UpperCamelCase ) lowerCAmelCase_ = pipe(**self.get_dummy_inputs(_UpperCamelCase ) ) lowerCAmelCase_ = output.images lowerCAmelCase_ = pipe( **self.get_dummy_inputs(_UpperCamelCase ) , return_dict=_UpperCamelCase , )[0] lowerCAmelCase_ = image[0, -3:, -3:, -1] lowerCAmelCase_ = image_from_tuple[0, -3:, -3:, -1] print(f"""image.shape {image.shape}""" ) assert image.shape == (1, 64, 64, 3) lowerCAmelCase_ = np.array( [0.8326919, 0.73790467, 0.20918581, 0.9309612, 0.5511791, 0.43713328, 0.5513321, 0.49922934, 0.59497786] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def __a ( self ) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): def __a ( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __a ( self ) -> Optional[int]: lowerCAmelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" ) lowerCAmelCase_ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) lowerCAmelCase_ = np.ones((768, 768) , dtype=np.floataa ) lowerCAmelCase_ = 0 lowerCAmelCase_ = "a hat" lowerCAmelCase_ = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(_UpperCamelCase ) lowerCAmelCase_ = KandinskyInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-inpaint" , torch_dtype=torch.floataa ) lowerCAmelCase_ = pipeline.to(_UpperCamelCase ) pipeline.set_progress_bar_config(disable=_UpperCamelCase ) lowerCAmelCase_ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase_ , lowerCAmelCase_ = pipe_prior( _UpperCamelCase , generator=_UpperCamelCase , num_inference_steps=5 , negative_prompt="" , ).to_tuple() lowerCAmelCase_ = pipeline( _UpperCamelCase , image=_UpperCamelCase , mask_image=_UpperCamelCase , image_embeds=_UpperCamelCase , negative_image_embeds=_UpperCamelCase , generator=_UpperCamelCase , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) lowerCAmelCase_ = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_UpperCamelCase , _UpperCamelCase )
704
import math class _lowerCAmelCase : def __init__( self , _UpperCamelCase=0 ) -> Tuple: # a graph with Node 0,1,...,N-1 lowerCAmelCase_ = n lowerCAmelCase_ = [ [math.inf for j in range(0 , _UpperCamelCase )] for i in range(0 , _UpperCamelCase ) ] # adjacency matrix for weight lowerCAmelCase_ = [ [math.inf for j in range(0 , _UpperCamelCase )] for i in range(0 , _UpperCamelCase ) ] # dp[i][j] stores minimum distance from i to j def __a ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]: lowerCAmelCase_ = w def __a ( self ) -> List[str]: for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): lowerCAmelCase_ = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def __a ( self , _UpperCamelCase , _UpperCamelCase ) -> Dict: return self.dp[u][v] if __name__ == "__main__": _A = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
279
0
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _A = "\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _A = "\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _A = "\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): def __a ( self ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/krishnap25/mauve" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/krishnap25/mauve"] , reference_urls=[ "https://arxiv.org/abs/2102.01454", "https://github.com/krishnap25/mauve", ] , ) def __a ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase="auto" , _UpperCamelCase=-1 , _UpperCamelCase=0.9 , _UpperCamelCase=5 , _UpperCamelCase=500 , _UpperCamelCase="gpt2-large" , _UpperCamelCase=-1 , _UpperCamelCase=1_024 , _UpperCamelCase=25 , _UpperCamelCase=5 , _UpperCamelCase=True , _UpperCamelCase=25 , ) -> Union[str, Any]: lowerCAmelCase_ = compute_mauve( p_text=lowerCAmelCase__ , q_text=lowerCAmelCase__ , p_features=lowerCAmelCase__ , q_features=lowerCAmelCase__ , p_tokens=lowerCAmelCase__ , q_tokens=lowerCAmelCase__ , num_buckets=lowerCAmelCase__ , pca_max_data=lowerCAmelCase__ , kmeans_explained_var=lowerCAmelCase__ , kmeans_num_redo=lowerCAmelCase__ , kmeans_max_iter=lowerCAmelCase__ , featurize_model_name=lowerCAmelCase__ , device_id=lowerCAmelCase__ , max_text_length=lowerCAmelCase__ , divergence_curve_discretization_size=lowerCAmelCase__ , mauve_scaling_factor=lowerCAmelCase__ , verbose=lowerCAmelCase__ , seed=lowerCAmelCase__ , ) return out
290
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run __magic_name__: str = True except (ImportError, AttributeError): __magic_name__: Dict = object def UpperCamelCase ( *_A, **_A ): """simple docstring""" pass __magic_name__: Dict = False __magic_name__: Optional[int] = logging.get_logger("transformers-cli/serving") def UpperCamelCase ( _A ): """simple docstring""" __magic_name__ : Tuple = pipeline( task=args.task, model=args.model if args.model else None, config=args.config, tokenizer=args.tokenizer, device=args.device, ) return ServeCommand(_A, args.host, args.port, args.workers ) class snake_case__ ( _lowerCAmelCase ): lowercase__ : dict class snake_case__ ( _lowerCAmelCase ): lowercase__ : List[str] lowercase__ : Optional[List[int]] class snake_case__ ( _lowerCAmelCase ): lowercase__ : str class snake_case__ ( _lowerCAmelCase ): lowercase__ : Any class snake_case__ ( _lowerCAmelCase ): @staticmethod def __magic_name__ ( lowerCAmelCase__ ) -> Any: __magic_name__ : List[str] = parser.add_parser( """serve""" , help="""CLI tool to run inference requests through REST and GraphQL endpoints.""" ) serve_parser.add_argument( """--task""" , type=lowerCAmelCase__ , choices=get_supported_tasks() , help="""The task to run the pipeline on""" , ) serve_parser.add_argument("""--host""" , type=lowerCAmelCase__ , default="""localhost""" , help="""Interface the server will listen on.""" ) serve_parser.add_argument("""--port""" , type=lowerCAmelCase__ , default=88_88 , help="""Port the serving will listen to.""" ) serve_parser.add_argument("""--workers""" , type=lowerCAmelCase__ , default=1 , help="""Number of http workers""" ) serve_parser.add_argument("""--model""" , type=lowerCAmelCase__ , help="""Model's name or path to stored model.""" ) serve_parser.add_argument("""--config""" , type=lowerCAmelCase__ , help="""Model's config name or path to stored model.""" ) serve_parser.add_argument("""--tokenizer""" , type=lowerCAmelCase__ , help="""Tokenizer name to use.""" ) serve_parser.add_argument( """--device""" , type=lowerCAmelCase__ , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) serve_parser.set_defaults(func=lowerCAmelCase__ ) def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: __magic_name__ : List[str] = pipeline __magic_name__ : Any = host __magic_name__ : List[str] = port __magic_name__ : Any = workers if not _serve_dependencies_installed: raise RuntimeError( """Using serve command requires FastAPI and uvicorn. """ """Please install transformers with [serving]: pip install \"transformers[serving]\".""" """Or install FastAPI and uvicorn separately.""" ) else: logger.info(F'Serving model over {host}:{port}' ) __magic_name__ : Any = FastAPI( routes=[ APIRoute( """/""" , self.model_info , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=["""GET"""] , ), APIRoute( """/tokenize""" , self.tokenize , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=["""POST"""] , ), APIRoute( """/detokenize""" , self.detokenize , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=["""POST"""] , ), APIRoute( """/forward""" , self.forward , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=["""POST"""] , ), ] , timeout=6_00 , ) def __magic_name__ ( self ) -> Union[str, Any]: run(self._app , host=self.host , port=self.port , workers=self.workers ) def __magic_name__ ( self ) -> List[Any]: return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def __magic_name__ ( self , lowerCAmelCase__ = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , lowerCAmelCase__ = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) ) -> str: try: __magic_name__ : Dict = self._pipeline.tokenizer.tokenize(lowerCAmelCase__ ) if return_ids: __magic_name__ : int = self._pipeline.tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) return ServeTokenizeResult(tokens=lowerCAmelCase__ , tokens_ids=lowerCAmelCase__ ) else: return ServeTokenizeResult(tokens=lowerCAmelCase__ ) except Exception as e: raise HTTPException(status_code=5_00 , detail={"""model""": """""", """error""": str(lowerCAmelCase__ )} ) def __magic_name__ ( self , lowerCAmelCase__ = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , lowerCAmelCase__ = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , lowerCAmelCase__ = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , ) -> Union[str, Any]: try: __magic_name__ : List[Any] = self._pipeline.tokenizer.decode(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return ServeDeTokenizeResult(model="""""" , text=lowerCAmelCase__ ) except Exception as e: raise HTTPException(status_code=5_00 , detail={"""model""": """""", """error""": str(lowerCAmelCase__ )} ) async def __magic_name__ ( self , lowerCAmelCase__=Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) ) -> Any: # Check we don't have empty string if len(lowerCAmelCase__ ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model __magic_name__ : Union[str, Any] = self._pipeline(lowerCAmelCase__ ) return ServeForwardResult(output=lowerCAmelCase__ ) except Exception as e: raise HTTPException(5_00 , {"""error""": str(lowerCAmelCase__ )} )
324
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A : Optional[int] = { '''configuration_mobilebert''': [ '''MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileBertConfig''', '''MobileBertOnnxConfig''', ], '''tokenization_mobilebert''': ['''MobileBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Any = ['''MobileBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] = [ '''MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileBertForMaskedLM''', '''MobileBertForMultipleChoice''', '''MobileBertForNextSentencePrediction''', '''MobileBertForPreTraining''', '''MobileBertForQuestionAnswering''', '''MobileBertForSequenceClassification''', '''MobileBertForTokenClassification''', '''MobileBertLayer''', '''MobileBertModel''', '''MobileBertPreTrainedModel''', '''load_tf_weights_in_mobilebert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Optional[Any] = [ '''TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileBertForMaskedLM''', '''TFMobileBertForMultipleChoice''', '''TFMobileBertForNextSentencePrediction''', '''TFMobileBertForPreTraining''', '''TFMobileBertForQuestionAnswering''', '''TFMobileBertForSequenceClassification''', '''TFMobileBertForTokenClassification''', '''TFMobileBertMainLayer''', '''TFMobileBertModel''', '''TFMobileBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys _A : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
711
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class _lowercase : '''simple docstring''' def __init__( self : Tuple ) -> Any: __lowerCAmelCase = {} def a ( self : Dict , SCREAMING_SNAKE_CASE__ : str ) -> None: __lowerCAmelCase = {} def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : float ) -> None: if nodea not in self.connections: self.add_node(SCREAMING_SNAKE_CASE__ ) if nodea not in self.connections: self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = probability def a ( self : Union[str, Any] ) -> list[str]: return list(self.connections ) def a ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> str: __lowerCAmelCase = 0 __lowerCAmelCase = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def UpperCamelCase_ ( snake_case_ : str , snake_case_ : list[tuple[str, str, float]] , snake_case_ : int ) -> dict[str, int]: '''simple docstring''' __lowerCAmelCase = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(snake_case_ , snake_case_ , snake_case_ ) __lowerCAmelCase = Counter(graph.get_nodes() ) __lowerCAmelCase = start for _ in range(snake_case_ ): __lowerCAmelCase = graph.transition(snake_case_ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
330
0
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin snake_case__ = get_tests_dir('''fixtures/spiece.model''') @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( _a ,unittest.TestCase): lowerCamelCase_ = AlbertTokenizer lowerCamelCase_ = AlbertTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = True lowerCamelCase_ = True def _snake_case ( self : Optional[int] ) ->Tuple: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing a__ :List[Any] = AlbertTokenizer(__A ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self : str , __A : Union[str, Any] ) ->str: """simple docstring""" a__ :Union[str, Any] = "this is a test" a__ :List[Any] = "this is a test" return input_text, output_text def _snake_case ( self : Dict ) ->Optional[Any]: """simple docstring""" a__ :Optional[int] = "<pad>" a__ :Dict = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__A ) , __A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__A ) , __A ) def _snake_case ( self : List[Any] ) ->int: """simple docstring""" a__ :int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "▁eloquent" ) self.assertEqual(len(__A ) , 30000 ) def _snake_case ( self : Optional[int] ) ->Any: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 30000 ) def _snake_case ( self : List[str] ) ->List[Any]: """simple docstring""" if not self.test_rust_tokenizer: return a__ :List[Any] = self.get_tokenizer() a__ :Tuple = self.get_rust_tokenizer() a__ :Optional[int] = "I was born in 92000, and this is falsé." a__ :Tuple = tokenizer.tokenize(__A ) a__ :List[str] = rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a__ :int = tokenizer.encode(__A , add_special_tokens=__A ) a__ :List[str] = rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a__ :List[Any] = self.get_rust_tokenizer() a__ :Optional[int] = tokenizer.encode(__A ) a__ :Optional[Any] = rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def _snake_case ( self : Tuple ) ->Optional[int]: """simple docstring""" a__ :Tuple = AlbertTokenizer(__A , keep_accents=__A ) a__ :Tuple = tokenizer.tokenize("This is a test" ) self.assertListEqual(__A , ["▁this", "▁is", "▁a", "▁test"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [48, 25, 21, 1289] ) a__ :Optional[int] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __A , ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "."] ) a__ :Tuple = tokenizer.convert_tokens_to_ids(__A ) self.assertListEqual(__A , [31, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] ) a__ :List[Any] = tokenizer.convert_ids_to_tokens(__A ) self.assertListEqual( __A , ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "."] , ) def _snake_case ( self : Union[str, Any] ) ->str: """simple docstring""" a__ :Tuple = AlbertTokenizer(__A ) a__ :Optional[Any] = tokenizer.encode("sequence builders" ) a__ :Any = tokenizer.encode("multi-sequence build" ) a__ :Tuple = tokenizer.build_inputs_with_special_tokens(__A ) a__ :Optional[Any] = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def _snake_case ( self : str ) ->Optional[int]: """simple docstring""" a__ :Any = {"attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "input_ids": [[2, 21970, 13, 5, 6092, 167, 28, 7103, 2153, 673, 8, 7028, 12051, 18, 17, 7103, 2153, 673, 8, 3515, 18684, 8, 4461, 6, 1927, 297, 8, 12060, 2607, 18, 13, 5, 4461, 15, 10538, 38, 8, 135, 15, 822, 58, 15, 993, 10363, 15, 1460, 8005, 4461, 15, 993, 255, 2328, 9, 9, 9, 6, 26, 1112, 816, 3260, 13, 5, 103, 2377, 6, 17, 1112, 816, 2782, 13, 5, 103, 10641, 6, 29, 84, 2512, 2430, 782, 18684, 2761, 19, 808, 2430, 2556, 17, 855, 1480, 9477, 4091, 128, 11712, 15, 7103, 2153, 673, 17, 24883, 9990, 9, 3], [2, 11502, 25, 1006, 20, 782, 8, 11809, 855, 1732, 19393, 18667, 37, 367, 21018, 69, 1854, 34, 11860, 19124, 27, 156, 225, 17, 193, 4141, 19, 65, 9124, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2231, 886, 2385, 17659, 84, 14, 16792, 1952, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="albert-base-v2" , revision="6b6560eaf5ff2e250b00c50f380c5389a9c2d82e" , )
395
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 # ######################################################################## snake_case__ = 16 snake_case__ = 32 def lowerCamelCase__ ( a : Accelerator , a : int = 16 ) -> int: """simple docstring""" a__ :Tuple = AutoTokenizer.from_pretrained("bert-base-cased" ) a__ :int = load_dataset("glue" , "mrpc" ) def tokenize_function(a : List[Any] ): # max_length=None => use the model max length (it's actually the default) a__ :Optional[int] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=a , max_length=a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a__ :Union[str, Any] = datasets.map( a , batched=a , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a__ :Optional[int] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(a : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. a__ :Dict = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a__ :List[str] = 16 elif accelerator.mixed_precision != "no": a__ :Optional[int] = 8 else: a__ :Tuple = None return tokenizer.pad( a , padding="longest" , max_length=a , pad_to_multiple_of=a , return_tensors="pt" , ) # Instantiate dataloaders. a__ :str = DataLoader( tokenized_datasets["train"] , shuffle=a , collate_fn=a , batch_size=a , drop_last=a ) a__ :str = DataLoader( tokenized_datasets["validation"] , shuffle=a , collate_fn=a , batch_size=a , drop_last=(accelerator.mixed_precision == "fp8") , ) return train_dataloader, eval_dataloader def lowerCamelCase__ ( a : List[str] , a : Dict ) -> List[str]: """simple docstring""" # Initialize accelerator a__ :Optional[int] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ :Optional[int] = config["lr"] a__ :List[str] = int(config["num_epochs"] ) a__ :List[Any] = int(config["seed"] ) a__ :List[Any] = int(config["batch_size"] ) a__ :Any = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation a__ :str = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: a__ :Tuple = batch_size // MAX_GPU_BATCH_SIZE a__ :List[str] = MAX_GPU_BATCH_SIZE set_seed(a ) a__ , a__ :Tuple = get_dataloaders(a , a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a__ :List[Any] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a__ :int = model.to(accelerator.device ) # Instantiate optimizer a__ :Any = AdamW(params=model.parameters() , lr=a ) # Instantiate scheduler a__ :Union[str, Any] = get_linear_schedule_with_warmup( optimizer=a , num_warmup_steps=100 , num_training_steps=(len(a ) * 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. a__ , a__ , a__ , a__ , a__ :Any = accelerator.prepare( a , a , a , a , a ) # Now we train the model for epoch in range(a ): model.train() for step, batch in enumerate(a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) a__ :List[str] = model(**a ) a__ :Union[str, Any] = outputs.loss a__ :str = loss / gradient_accumulation_steps accelerator.backward(a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a__ :Optional[int] = model(**a ) a__ :str = outputs.logits.argmax(dim=-1 ) a__ , a__ :List[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=a , references=a , ) a__ :Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , a ) def lowerCamelCase__ ( ) -> Any: """simple docstring""" a__ :List[str] = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=a , default=a , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) a__ :Union[str, Any] = parser.parse_args() a__ :Optional[Any] = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(a , a ) if __name__ == "__main__": main()
395
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case__ : Optional[Any] = { """configuration_instructblip""": [ """INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """InstructBlipConfig""", """InstructBlipQFormerConfig""", """InstructBlipVisionConfig""", ], """processing_instructblip""": ["""InstructBlipProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : Optional[int] = [ """INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """InstructBlipQFormerModel""", """InstructBlipPreTrainedModel""", """InstructBlipForConditionalGeneration""", """InstructBlipVisionModel""", ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys snake_case__ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
655
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), F"""Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), F"""Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})""" def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True ): model.train() __lowercase = model(_SCREAMING_SNAKE_CASE ) __lowercase = F.mse_loss(_SCREAMING_SNAKE_CASE , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(_SCREAMING_SNAKE_CASE ) def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ): set_seed(4_2 ) __lowercase = RegressionModel() __lowercase = deepcopy(_SCREAMING_SNAKE_CASE ) __lowercase = RegressionDataset(length=8_0 ) __lowercase = DataLoader(_SCREAMING_SNAKE_CASE , batch_size=1_6 ) model.to(accelerator.device ) if sched: __lowercase = AdamW(params=model.parameters() , lr=1E-3 ) __lowercase = AdamW(params=ddp_model.parameters() , lr=1E-3 ) __lowercase = LambdaLR(_SCREAMING_SNAKE_CASE , lr_lambda=lambda _SCREAMING_SNAKE_CASE : epoch**0.6_5 ) __lowercase = LambdaLR(_SCREAMING_SNAKE_CASE , lr_lambda=lambda _SCREAMING_SNAKE_CASE : epoch**0.6_5 ) # Make a copy of `model` if sched: __lowercase , __lowercase , __lowercase , __lowercase = accelerator.prepare(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __lowercase , __lowercase = accelerator.prepare(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def snake_case_ ( _SCREAMING_SNAKE_CASE ): # Test when on a single CPU or GPU that the context manager does nothing __lowercase , __lowercase , __lowercase = get_training_setup(_SCREAMING_SNAKE_CASE ) # Use a single batch __lowercase , __lowercase = next(iter(_SCREAMING_SNAKE_CASE ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model __lowercase , __lowercase = accelerator.gather((ddp_input, ddp_target) ) __lowercase , __lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(_SCREAMING_SNAKE_CASE ): step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: # Sync grads step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), F"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) __lowercase = ddp_input[torch.randperm(len(_SCREAMING_SNAKE_CASE ) )] def snake_case_ ( _SCREAMING_SNAKE_CASE ): # Test on distributed setup that context manager behaves properly __lowercase , __lowercase , __lowercase = get_training_setup(_SCREAMING_SNAKE_CASE ) # Use a single batch __lowercase , __lowercase = next(iter(_SCREAMING_SNAKE_CASE ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model __lowercase , __lowercase = accelerator.gather((ddp_input, ddp_target) ) __lowercase , __lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(_SCREAMING_SNAKE_CASE ): step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: # Sync grads step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F"""Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) __lowercase = ddp_input[torch.randperm(len(_SCREAMING_SNAKE_CASE ) )] def snake_case_ ( _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ): __lowercase = Accelerator( split_batches=_SCREAMING_SNAKE_CASE , dispatch_batches=_SCREAMING_SNAKE_CASE , gradient_accumulation_steps=2 ) # Test that context manager behaves properly __lowercase , __lowercase , __lowercase = get_training_setup(_SCREAMING_SNAKE_CASE ) for iteration, batch in enumerate(_SCREAMING_SNAKE_CASE ): __lowercase , __lowercase = batch.values() # Gather the distributed inputs and targs for the base model __lowercase , __lowercase = accelerator.gather((ddp_input, ddp_target) ) __lowercase , __lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Do "gradient accumulation" (noop) with accelerator.accumulate(_SCREAMING_SNAKE_CASE ): step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(_SCREAMING_SNAKE_CASE ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F"""Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F"""Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) __lowercase = ddp_input[torch.randperm(len(_SCREAMING_SNAKE_CASE ) )] GradientState._reset_state() def snake_case_ ( _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ): __lowercase = Accelerator( split_batches=_SCREAMING_SNAKE_CASE , dispatch_batches=_SCREAMING_SNAKE_CASE , gradient_accumulation_steps=2 ) # Test that context manager behaves properly __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase = get_training_setup(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for iteration, batch in enumerate(_SCREAMING_SNAKE_CASE ): __lowercase , __lowercase = batch.values() # Gather the distributed inputs and targs for the base model __lowercase , __lowercase = accelerator.gather((ddp_input, ddp_target) ) __lowercase , __lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(_SCREAMING_SNAKE_CASE )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(_SCREAMING_SNAKE_CASE ): step_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), F"""Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n""" __lowercase = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(_SCREAMING_SNAKE_CASE )) if accelerator.num_processes > 1: check_model_parameters(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) GradientState._reset_state() def snake_case_ ( ): __lowercase = Accelerator() __lowercase = RegressionDataset(length=8_0 ) __lowercase = DataLoader(_SCREAMING_SNAKE_CASE , batch_size=1_6 ) __lowercase = RegressionDataset(length=9_6 ) __lowercase = DataLoader(_SCREAMING_SNAKE_CASE , batch_size=1_6 ) __lowercase , __lowercase = accelerator.prepare(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(_SCREAMING_SNAKE_CASE ): assert id(accelerator.gradient_state.active_dataloader ) == id(_SCREAMING_SNAKE_CASE ) if iteration < len(_SCREAMING_SNAKE_CASE ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(_SCREAMING_SNAKE_CASE ): assert id(accelerator.gradient_state.active_dataloader ) == id(_SCREAMING_SNAKE_CASE ) if batch_num < len(_SCREAMING_SNAKE_CASE ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def snake_case_ ( ): __lowercase = Accelerator() __lowercase = accelerator.state if state.local_process_index == 0: print("**Test `accumulate` gradient accumulation with dataloader break**" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("**Test NOOP `no_sync` context manager**" ) test_noop_sync(_SCREAMING_SNAKE_CASE ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("**Test Distributed `no_sync` context manager**" ) test_distributed_sync(_SCREAMING_SNAKE_CASE ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation, " , F"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" , ) test_gradient_accumulation(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("<" , "2.0" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation with optimizer and scheduler, " , "`split_batches=False`, `dispatch_batches=False`**" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation with optimizer and scheduler, " , F"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" , ) test_gradient_accumulation_with_opt_and_scheduler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def snake_case_ ( _SCREAMING_SNAKE_CASE ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
655
1
'''simple docstring''' from __future__ import annotations import typing from collections.abc import Iterable import numpy as np A__ : Dict = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 A__ : Optional[Any] = typing.Union[np.floataa, int, float] # noqa: UP007 def UpperCAmelCase__ ( UpperCAmelCase_ : Vector , UpperCAmelCase_ : Vector ) -> VectorOut: return np.sqrt(np.sum((np.asarray(UpperCAmelCase_ ) - np.asarray(UpperCAmelCase_ )) ** 2 ) ) def UpperCAmelCase__ ( UpperCAmelCase_ : Vector , UpperCAmelCase_ : Vector ) -> VectorOut: return sum((va - va) ** 2 for va, va in zip(UpperCAmelCase_ , UpperCAmelCase_ ) ) ** (1 / 2) if __name__ == "__main__": def UpperCAmelCase__ ( ) -> None: from timeit import timeit print('Without Numpy' ) print( timeit( 'euclidean_distance_no_np([1, 2, 3], [4, 5, 6])' , number=1_00_00 , globals=globals() , ) ) print('With Numpy' ) print( timeit( 'euclidean_distance([1, 2, 3], [4, 5, 6])' , number=1_00_00 , globals=globals() , ) ) benchmark()
13
'''simple docstring''' def __UpperCamelCase ( lowercase__ : list[int] ): '''simple docstring''' if not nums: # Makes sure that the list is not empty raise ValueError('List is empty' ) __lowercase =sum(lowercase__ ) / len(lowercase__ ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(lowercase__ ) if __name__ == "__main__": import doctest doctest.testmod()
119
0
from math import pi def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> float: return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
38
from PIL import Image def A_ ( _lowerCAmelCase ) -> Image: UpperCamelCase , UpperCamelCase : List[Any] = image.size UpperCamelCase : Union[str, Any] = 0 UpperCamelCase : List[str] = image.load() for i in range(_lowerCAmelCase ): for j in range(_lowerCAmelCase ): UpperCamelCase : List[Any] = pixels[j, i] mean += pixel mean //= width * height for j in range(_lowerCAmelCase ): for i in range(_lowerCAmelCase ): UpperCamelCase : Union[str, Any] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": __lowerCamelCase : Union[str, Any] = mean_threshold(Image.open("""path_to_image""").convert("""L""")) image.save("""output_image_path""")
38
1
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] 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(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
1
'''simple docstring''' def _a ( _SCREAMING_SNAKE_CASE : Any ): _SCREAMING_SNAKE_CASE = [0] * len(_SCREAMING_SNAKE_CASE ) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = [1] * len(_SCREAMING_SNAKE_CASE ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_SCREAMING_SNAKE_CASE ) ): if indegree[i] == 0: queue.append(_SCREAMING_SNAKE_CASE ) while queue: _SCREAMING_SNAKE_CASE = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: _SCREAMING_SNAKE_CASE = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_SCREAMING_SNAKE_CASE ) print(max(_SCREAMING_SNAKE_CASE ) ) # Adjacency list of Graph _snake_case : Optional[int] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
493
'''simple docstring''' import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowerCAmelCase ( __UpperCAmelCase ): a : Optional[int] = ["""image_processor""", """tokenizer"""] a : Optional[int] = """BlipImageProcessor""" a : Optional[int] = """AutoTokenizer""" def __init__( self , UpperCamelCase , UpperCamelCase , UpperCamelCase ): super().__init__(UpperCamelCase , UpperCamelCase ) # add QFormer tokenizer _SCREAMING_SNAKE_CASE = qformer_tokenizer def __call__( self , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = True , UpperCamelCase = False , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = 0 , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = False , UpperCamelCase = False , UpperCamelCase = False , UpperCamelCase = False , UpperCamelCase = False , UpperCamelCase = True , UpperCamelCase = None , **UpperCamelCase , ): if images is None and text is None: raise ValueError("You have to specify at least images or text." ) _SCREAMING_SNAKE_CASE = BatchFeature() if text is not None: _SCREAMING_SNAKE_CASE = self.tokenizer( text=UpperCamelCase , add_special_tokens=UpperCamelCase , padding=UpperCamelCase , truncation=UpperCamelCase , max_length=UpperCamelCase , stride=UpperCamelCase , pad_to_multiple_of=UpperCamelCase , return_attention_mask=UpperCamelCase , return_overflowing_tokens=UpperCamelCase , return_special_tokens_mask=UpperCamelCase , return_offsets_mapping=UpperCamelCase , return_token_type_ids=UpperCamelCase , return_length=UpperCamelCase , verbose=UpperCamelCase , return_tensors=UpperCamelCase , **UpperCamelCase , ) encoding.update(UpperCamelCase ) _SCREAMING_SNAKE_CASE = self.qformer_tokenizer( text=UpperCamelCase , add_special_tokens=UpperCamelCase , padding=UpperCamelCase , truncation=UpperCamelCase , max_length=UpperCamelCase , stride=UpperCamelCase , pad_to_multiple_of=UpperCamelCase , return_attention_mask=UpperCamelCase , return_overflowing_tokens=UpperCamelCase , return_special_tokens_mask=UpperCamelCase , return_offsets_mapping=UpperCamelCase , return_token_type_ids=UpperCamelCase , return_length=UpperCamelCase , verbose=UpperCamelCase , return_tensors=UpperCamelCase , **UpperCamelCase , ) _SCREAMING_SNAKE_CASE = qformer_text_encoding.pop("input_ids" ) _SCREAMING_SNAKE_CASE = qformer_text_encoding.pop("attention_mask" ) if images is not None: _SCREAMING_SNAKE_CASE = self.image_processor(UpperCamelCase , return_tensors=UpperCamelCase ) encoding.update(UpperCamelCase ) return encoding def lowercase ( self , *UpperCamelCase , **UpperCamelCase ): return self.tokenizer.batch_decode(*UpperCamelCase , **UpperCamelCase ) def lowercase ( self , *UpperCamelCase , **UpperCamelCase ): return self.tokenizer.decode(*UpperCamelCase , **UpperCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def lowercase ( self ): _SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def lowercase ( self , UpperCamelCase , **UpperCamelCase ): if os.path.isfile(UpperCamelCase ): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(UpperCamelCase , exist_ok=UpperCamelCase ) _SCREAMING_SNAKE_CASE = os.path.join(UpperCamelCase , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(UpperCamelCase ) return super().save_pretrained(UpperCamelCase , **UpperCamelCase ) @classmethod def lowercase ( cls , UpperCamelCase , **UpperCamelCase ): _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(UpperCamelCase , subfolder="qformer_tokenizer" ) _SCREAMING_SNAKE_CASE = cls._get_arguments_from_pretrained(UpperCamelCase , **UpperCamelCase ) args.append(UpperCamelCase ) return cls(*UpperCamelCase )
493
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers 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 ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def __snake_case ( lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' __magic_name__ = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class UpperCamelCase_ ( A , A , A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Any = StableDiffusionLatentUpscalePipeline UpperCAmelCase__ : int = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''height''', '''width''', '''cross_attention_kwargs''', '''negative_prompt_embeds''', '''prompt_embeds''', } UpperCAmelCase__ : Optional[int] = PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''} UpperCAmelCase__ : List[str] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCAmelCase__ : Tuple = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCAmelCase__ : Tuple = frozenset([] ) UpperCAmelCase__ : Union[str, Any] = True @property def __A ( self : Optional[Any] ) -> int: __magic_name__ = 1 __magic_name__ = 4 __magic_name__ = (16, 16) __magic_name__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_lowerCamelCase ) return image def __A ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) __magic_name__ = UNetaDConditionModel( act_fn="gelu" , attention_head_dim=8 , norm_num_groups=_lowerCamelCase , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=1_60 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=( "KDownBlock2D", "KCrossAttnDownBlock2D", "KCrossAttnDownBlock2D", "KCrossAttnDownBlock2D", ) , in_channels=8 , mid_block_type=_lowerCamelCase , only_cross_attention=_lowerCamelCase , out_channels=5 , resnet_time_scale_shift="scale_shift" , time_embedding_type="fourier" , timestep_post_act="gelu" , up_block_types=("KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KUpBlock2D") , ) __magic_name__ = AutoencoderKL( block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", ] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) __magic_name__ = EulerDiscreteScheduler(prediction_type="sample" ) __magic_name__ = 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=10_00 , hidden_act="quick_gelu" , projection_dim=5_12 , ) __magic_name__ = CLIPTextModel(_lowerCamelCase ) __magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __magic_name__ = { "unet": model.eval(), "vae": vae.eval(), "scheduler": scheduler, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def __A ( self : str , _lowerCamelCase : Optional[int] , _lowerCamelCase : List[Any]=0 ) -> Any: if str(_lowerCamelCase ).startswith("mps" ): __magic_name__ = torch.manual_seed(_lowerCamelCase ) else: __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __magic_name__ = { "prompt": "A painting of a squirrel eating a burger", "image": self.dummy_image.cpu(), "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def __A ( self : Dict ) -> int: __magic_name__ = "cpu" __magic_name__ = self.get_dummy_components() __magic_name__ = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = self.get_dummy_inputs(_lowerCamelCase ) __magic_name__ = pipe(**_lowerCamelCase ).images __magic_name__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 2_56, 2_56, 3) ) __magic_name__ = np.array( [0.47_222_412, 0.41_921_633, 0.44_717_434, 0.46_874_192, 0.42_588_258, 0.46_150_726, 0.4_677_534, 0.45_583_832, 0.48_579_055] ) __magic_name__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __A ( self : List[str] ) -> List[Any]: super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 ) def __A ( self : str ) -> Dict: super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 ) def __A ( self : Any ) -> int: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __A ( self : str ) -> Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=7e-3 ) def __A ( self : str ) -> int: super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 ) def __A ( self : List[Any] ) -> Optional[int]: super().test_save_load_local(expected_max_difference=3e-3 ) def __A ( self : Union[str, Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __A ( self : Union[str, Any] ) -> Any: __magic_name__ = [ "DDIMScheduler", "DDPMScheduler", "PNDMScheduler", "HeunDiscreteScheduler", "EulerAncestralDiscreteScheduler", "KDPM2DiscreteScheduler", "KDPM2AncestralDiscreteScheduler", "DPMSolverSDEScheduler", ] __magic_name__ = self.get_dummy_components() __magic_name__ = self.pipeline_class(**_lowerCamelCase ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = self.get_dummy_inputs(_lowerCamelCase ) __magic_name__ = 2 __magic_name__ = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue __magic_name__ = getattr(_lowerCamelCase , scheduler_enum.name ) __magic_name__ = scheduler_cls.from_config(pipe.scheduler.config ) __magic_name__ = pipe(**_lowerCamelCase )[0] outputs.append(_lowerCamelCase ) assert check_same_shape(_lowerCamelCase ) @require_torch_gpu @slow class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Dict ) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ) -> Optional[int]: __magic_name__ = torch.manual_seed(33 ) __magic_name__ = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" , torch_dtype=torch.floataa ) pipe.to("cuda" ) __magic_name__ = StableDiffusionLatentUpscalePipeline.from_pretrained( "stabilityai/sd-x2-latent-upscaler" , torch_dtype=torch.floataa ) upscaler.to("cuda" ) __magic_name__ = "a photo of an astronaut high resolution, unreal engine, ultra realistic" __magic_name__ = pipe(_lowerCamelCase , generator=_lowerCamelCase , output_type="latent" ).images __magic_name__ = upscaler( prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=20 , guidance_scale=0 , generator=_lowerCamelCase , output_type="np" , ).images[0] __magic_name__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy" ) assert np.abs((expected_image - image).mean() ) < 5e-2 def __A ( self : Union[str, Any] ) -> str: __magic_name__ = torch.manual_seed(33 ) __magic_name__ = StableDiffusionLatentUpscalePipeline.from_pretrained( "stabilityai/sd-x2-latent-upscaler" , torch_dtype=torch.floataa ) upscaler.to("cuda" ) __magic_name__ = "the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas" __magic_name__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png" ) __magic_name__ = upscaler( prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=20 , guidance_scale=0 , generator=_lowerCamelCase , output_type="np" , ).images[0] __magic_name__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy" ) assert np.abs((expected_image - image).max() ) < 5e-2
664
'''simple docstring''' import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ ) __magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ ) __magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ ) __magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"] if config.model_type == "t5": __magic_name__ = "SelfAttention" if config.model_type == "longt5" and config.encoder_attention_type == "local": __magic_name__ = "LocalSelfAttention" elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = "TransientGlobalSelfAttention" else: raise ValueError( "Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`" " attribute with a value from ['local', 'transient-global]." ) # Encoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"] if split_mlp_wi: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_global_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = tax_mlp_layer_norm __magic_name__ = flax_model_encoder_layer_block # Only for layer 0: __magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_global_rel_embedding # Assigning __magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"] __magic_name__ = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][ "scale" ] # Encoder-Decoder-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"] __magic_name__ = tax_enc_dec_attention_module["key"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["out"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["query"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"] # MLP if split_mlp_wi: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_pre_attention_layer_norm __magic_name__ = tax_enc_dec_attention_key __magic_name__ = tax_enc_dec_attention_out __magic_name__ = tax_enc_dec_attention_query __magic_name__ = tax_enc_dec_attention_value __magic_name__ = tax_cross_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = txa_mlp_layer_norm __magic_name__ = flax_model_decoder_layer_block # Decoder Normalization __magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"] __magic_name__ = txa_decoder_norm # Only for layer 0: __magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_decoder_rel_embedding # Token Embeddings __magic_name__ = tax_model["target"]["token_embedder"]["embedding"] __magic_name__ = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"] flax_model.save_pretrained(lowerCamelCase_ ) print("T5X Model was sucessfully converted!" ) if __name__ == "__main__": __magic_name__ : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.' ) parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.') parser.add_argument( '--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.' ) __magic_name__ : Optional[int] =parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
664
1
import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class snake_case_ ( __a , unittest.TestCase): lowerCamelCase :Optional[int] = BlenderbotSmallTokenizer lowerCamelCase :Union[str, Any] = False def __lowercase ( self ) -> List[str]: super().setUp() lowerCamelCase : Any =['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] lowerCamelCase : Any =dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) lowerCamelCase : Optional[int] =['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] lowerCamelCase : Tuple ={'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} lowerCamelCase : Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowerCamelCase : List[str] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(snake_case__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(snake_case__ ) ) def __lowercase ( self , **__lowercase ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **snake_case__ ) def __lowercase ( self , __lowercase ) -> List[Any]: lowerCamelCase : Optional[int] ='''adapt act apte''' lowerCamelCase : Any ='''adapt act apte''' return input_text, output_text def __lowercase ( self ) -> Tuple: lowerCamelCase : List[Any] =BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCamelCase : List[Any] ='''adapt act apte''' lowerCamelCase : Optional[Any] =['''adapt''', '''act''', '''ap@@''', '''te'''] lowerCamelCase : Any =tokenizer.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) lowerCamelCase : List[Any] =[tokenizer.bos_token] + tokens + [tokenizer.eos_token] lowerCamelCase : Any =[0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) , snake_case__ ) def __lowercase ( self ) -> Optional[int]: lowerCamelCase : List[str] =BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [1_3_8_4] lowerCamelCase : int ='''I am a small frog.''' lowerCamelCase : Optional[Any] =tok([src_text] , padding=snake_case__ , truncation=snake_case__ )['''input_ids'''] lowerCamelCase : Optional[int] =tok.batch_decode(snake_case__ , skip_special_tokens=snake_case__ , clean_up_tokenization_spaces=snake_case__ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def __lowercase ( self ) -> Tuple: lowerCamelCase : Optional[Any] =BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) lowerCamelCase : str ='''I am a small frog .''' lowerCamelCase : Any ='''.''' lowerCamelCase : Union[str, Any] =tok(snake_case__ )['''input_ids'''] lowerCamelCase : Union[str, Any] =tok(snake_case__ )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
706
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available snake_case_ = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ '''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 snake_case_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
262
0
'''simple docstring''' from __future__ import annotations from math import pow, sqrt def lowerCamelCase ( _snake_case : float ,_snake_case : float ,_snake_case : float ): '''simple docstring''' if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance == 0: return {"resistance": sqrt(pow(_snake_case ,2 ) - pow(_snake_case ,2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(_snake_case ,2 ) - pow(_snake_case ,2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(_snake_case ,2 ) + pow(_snake_case ,2 ) )} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
267
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ = { "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] SCREAMING_SNAKE_CASE__ = ["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
267
1
'''simple docstring''' UpperCamelCase_ = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def lowerCamelCase ( UpperCAmelCase__ : dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict ) -> list[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[Any] = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE__ :Any = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE__ :List[str] = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE__ :Any = path[-1] if node not in explored: SCREAMING_SNAKE_CASE__ :List[str] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE__ :Optional[int] = list(UpperCAmelCase__ ) new_path.append(UpperCAmelCase__ ) queue.append(UpperCAmelCase__ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(UpperCAmelCase__ ) # in case there's no path between the 2 nodes return [] def lowerCamelCase ( UpperCAmelCase__ : dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> int: '''simple docstring''' if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE__ :Union[str, Any] = [start] SCREAMING_SNAKE_CASE__ :Union[str, Any] = set(UpperCAmelCase__ ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE__ :Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE__ :Tuple = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE__ :Optional[Any] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(UpperCAmelCase__ ) queue.append(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :Union[str, Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
703
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = {'''vocab_file''': '''sentencepiece.model'''} UpperCamelCase_ = { '''vocab_file''': { '''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''', }, } UpperCamelCase_ = { '''google/rembert''': 2_56, } class _SCREAMING_SNAKE_CASE( _SCREAMING_SNAKE_CASE ): A_ : Dict = VOCAB_FILES_NAMES A_ : List[str] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Dict=False , UpperCamelCase_ : Any=True , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : Tuple="[CLS]" , UpperCamelCase_ : Tuple="[SEP]" , UpperCamelCase_ : Union[str, Any]="[UNK]" , UpperCamelCase_ : List[Any]="[SEP]" , UpperCamelCase_ : Optional[Any]="[PAD]" , UpperCamelCase_ : List[str]="[CLS]" , UpperCamelCase_ : Tuple="[MASK]" , **UpperCamelCase_ : Any , ) -> Any: super().__init__( do_lower_case=UpperCamelCase_ , remove_space=UpperCamelCase_ , keep_accents=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , **UpperCamelCase_ , ) SCREAMING_SNAKE_CASE__ :Tuple = do_lower_case SCREAMING_SNAKE_CASE__ :Optional[int] = remove_space SCREAMING_SNAKE_CASE__ :Any = keep_accents SCREAMING_SNAKE_CASE__ :Union[str, Any] = vocab_file SCREAMING_SNAKE_CASE__ :int = spm.SentencePieceProcessor() self.sp_model.Load(UpperCamelCase_ ) @property def __lowerCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: return len(self.sp_model ) def __lowerCamelCase ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ :Union[str, Any] = {self.convert_ids_to_tokens(UpperCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) -> Dict: SCREAMING_SNAKE_CASE__ :Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE__ :Optional[int] = None return state def __setstate__( self : int , UpperCamelCase_ : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ :Optional[int] = d SCREAMING_SNAKE_CASE__ :str = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def __lowerCamelCase ( self : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : int=False ) -> Any: SCREAMING_SNAKE_CASE__ :Tuple = self.sp_model.EncodeAsPieces(UpperCamelCase_ ) return pieces def __lowerCamelCase ( self : Any , UpperCamelCase_ : Union[str, Any] ) -> int: return self.sp_model.PieceToId(UpperCamelCase_ ) def __lowerCamelCase ( self : Any , UpperCamelCase_ : List[str] ) -> Any: return self.sp_model.IdToPiece(UpperCamelCase_ ) def __lowerCamelCase ( self : Union[str, Any] , UpperCamelCase_ : int ) -> str: SCREAMING_SNAKE_CASE__ :Tuple = self.sp_model.decode_pieces(UpperCamelCase_ ) return out_string def __lowerCamelCase ( self : List[str] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ :Union[str, Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ :Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCamelCase ( self : Optional[int] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None , UpperCamelCase_ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] + ([0] * len(UpperCamelCase_ )) + [1] return [1] + ([0] * len(UpperCamelCase_ )) + [1] def __lowerCamelCase ( self : List[str] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ :Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE__ :Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCamelCase ( self : Any , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCamelCase_ ): logger.error('Vocabulary path ({}) should be a directory'.format(UpperCamelCase_ ) ) return SCREAMING_SNAKE_CASE__ :Optional[Any] = os.path.join( UpperCamelCase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ): copyfile(self.vocab_file , UpperCamelCase_ ) return (out_vocab_file,)
320
0
import requests def __lowercase ( snake_case, snake_case ): """simple docstring""" __magic_name__ :Dict = {'''Content-Type''': '''application/json'''} __magic_name__ :Union[str, Any] = requests.post(snake_case, json={'''text''': message_body}, headers=snake_case ) if response.status_code != 2_0_0: __magic_name__ :Any = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(snake_case ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("""<YOUR MESSAGE BODY>""", """<SLACK CHANNEL URL>""")
0
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass lowerCamelCase =(3, 9, -1_1, 0, 7, 5, 1, -1) lowerCamelCase =(4, 6, 2, 0, 8, 1_0, 3, -2) @dataclass class _lowerCamelCase : """simple docstring""" SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 class _lowerCamelCase : """simple docstring""" def __init__( self , __SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase__ : Node | None = None for i in sorted(__SCREAMING_SNAKE_CASE , reverse=__SCREAMING_SNAKE_CASE ): UpperCamelCase__ : List[str] = Node(__SCREAMING_SNAKE_CASE , self.head ) def __iter__( self ) -> Iterator[int]: """simple docstring""" UpperCamelCase__ : int = self.head while node: yield node.data UpperCamelCase__ : List[Any] = node.next_node def __len__( self ) -> int: """simple docstring""" return sum(1 for _ in self ) def __str__( self ) -> str: """simple docstring""" return " -> ".join([str(__SCREAMING_SNAKE_CASE ) for node in self] ) def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ , UpperCamelCase__ ): return SortedLinkedList(list(UpperCamelCase__ ) + list(UpperCamelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase =SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
285
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class UpperCAmelCase ( _UpperCAmelCase ): '''simple docstring''' lowerCAmelCase_ = """roc_bert""" def __init__( self : int , __lowercase : List[Any]=3_05_22 , __lowercase : Optional[Any]=7_68 , __lowercase : Optional[Any]=12 , __lowercase : List[Any]=12 , __lowercase : Tuple=30_72 , __lowercase : Tuple="gelu" , __lowercase : Dict=0.1 , __lowercase : List[str]=0.1 , __lowercase : Tuple=5_12 , __lowercase : Tuple=2 , __lowercase : List[str]=0.02 , __lowercase : Tuple=1E-12 , __lowercase : Any=True , __lowercase : List[Any]=0 , __lowercase : Tuple="absolute" , __lowercase : List[Any]=None , __lowercase : List[str]=True , __lowercase : List[Any]=True , __lowercase : Dict=7_68 , __lowercase : Optional[Any]=9_10 , __lowercase : List[str]=5_12 , __lowercase : Optional[int]=2_48_58 , __lowercase : List[str]=True , **__lowercase : List[str] , ): """simple docstring""" snake_case_ = vocab_size snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps snake_case_ = use_cache snake_case_ = enable_pronunciation snake_case_ = enable_shape snake_case_ = pronunciation_embed_dim snake_case_ = pronunciation_vocab_size snake_case_ = shape_embed_dim snake_case_ = shape_vocab_size snake_case_ = concat_input snake_case_ = position_embedding_type snake_case_ = classifier_dropout super().__init__(pad_token_id=lowercase__ , **lowercase__ )
704
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' lowerCAmelCase_ = DistilBertTokenizer lowerCAmelCase_ = DistilBertTokenizerFast lowerCAmelCase_ = True @slow def snake_case__ ( self : Tuple ): """simple docstring""" snake_case_ = DistilBertTokenizer.from_pretrained("distilbert-base-uncased" ) snake_case_ = tokenizer.encode("sequence builders" , add_special_tokens=__lowercase ) snake_case_ = tokenizer.encode("multi-sequence build" , add_special_tokens=__lowercase ) snake_case_ = tokenizer.build_inputs_with_special_tokens(__lowercase ) snake_case_ = tokenizer.build_inputs_with_special_tokens(__lowercase , __lowercase ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
139
0
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 _snake_case ( A__ ): def __init__( self , a , a=13 , a=7 , a=True , a=True , a=True , a=True , a=True , a=False , a=False , a=False , a=2 , a=99 , a=0 , a=32 , a=5 , a=4 , a=0.1 , a=0.1 , a=512 , a=12 , a=2 , a=0.02 , a=3 , a=4 , a="last" , a=None , a=None , ) -> Optional[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_lengths SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = gelu_activation SCREAMING_SNAKE_CASE = sinusoidal_embeddings SCREAMING_SNAKE_CASE = causal SCREAMING_SNAKE_CASE = asm SCREAMING_SNAKE_CASE = n_langs SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_special SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads 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 = summary_type SCREAMING_SNAKE_CASE = use_proj SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None if self.use_input_lengths: SCREAMING_SNAKE_CASE = ( ids_tensor([self.batch_size] , vocab_size=2) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.n_langs) 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] , 2).float() 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_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Dict: SCREAMING_SNAKE_CASE = FlaubertModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , lengths=a , langs=a) SCREAMING_SNAKE_CASE = model(a , langs=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 = FlaubertWithLMHeadModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , token_type_ids=a , labels=a) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Any: SCREAMING_SNAKE_CASE = FlaubertForQuestionAnsweringSimple(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) SCREAMING_SNAKE_CASE = model(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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Dict: SCREAMING_SNAKE_CASE = FlaubertForQuestionAnswering(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) SCREAMING_SNAKE_CASE = model( a , start_positions=a , end_positions=a , cls_index=a , is_impossible=a , p_mask=a , ) SCREAMING_SNAKE_CASE = model( a , start_positions=a , end_positions=a , cls_index=a , is_impossible=a , ) ((SCREAMING_SNAKE_CASE) , ) = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE = model(a , start_positions=a , end_positions=a) ((SCREAMING_SNAKE_CASE) , ) = 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = FlaubertForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Any: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = FlaubertForTokenClassification(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.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Tuple: SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = FlaubertForMultipleChoice(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : Any = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) _lowercase : 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a) -> Optional[int]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Any: SCREAMING_SNAKE_CASE = super()._prepare_for_class(a , a , return_labels=a) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a) SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaubertModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , emb_dim=37) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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_flaubert_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = FlaubertModel.from_pretrained(a) self.assertIsNotNone(a) @slow @require_torch_gpu def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(config=a) SCREAMING_SNAKE_CASE = self._prepare_for_class(a , a) SCREAMING_SNAKE_CASE = 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 = 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 _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = FlaubertModel.from_pretrained('flaubert/flaubert_base_cased') SCREAMING_SNAKE_CASE = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(a)[0] SCREAMING_SNAKE_CASE = torch.Size((1, 11, 768)) self.assertEqual(output.shape , a) SCREAMING_SNAKE_CASE = torch.tensor( [[[-2.62_51, -1.42_98, -0.02_27], [-2.85_10, -1.63_87, 0.22_58], [-2.81_14, -1.18_32, -0.30_66]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , a , atol=1E-4))
73
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class UpperCAmelCase__ : """simple docstring""" lowerCAmelCase__ : int lowerCAmelCase__ : TreeNode | None = None lowerCAmelCase__ : TreeNode | None = None a_ = namedtuple("""CoinsDistribResult""", """moves excess""") def __lowerCAmelCase ( A_ : TreeNode | None ) -> int: if root is None: return 0 # Validation def count_nodes(A_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(A_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(A_ ) != count_coins(A_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(A_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) __UpperCAmelCase , __UpperCAmelCase = get_distrib(node.left ) __UpperCAmelCase , __UpperCAmelCase = get_distrib(node.right ) __UpperCAmelCase = 1 - left_distrib_excess __UpperCAmelCase = 1 - right_distrib_excess __UpperCAmelCase = ( left_distrib_moves + right_distrib_moves + abs(A_ ) + abs(A_ ) ) __UpperCAmelCase = node.data - coins_to_left - coins_to_right return CoinsDistribResult(A_ , A_ ) return get_distrib(A_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
221
0
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : float ) -> float: """simple docstring""" if edge <= 0 or not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError("""Length must be a positive.""" ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : float ) -> float: """simple docstring""" if edge <= 0 or not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError("""Length must be a positive.""" ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
379
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : List[Any] = { '''configuration_informer''': [ '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Union[str, Any] = [ '''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InformerForPrediction''', '''InformerModel''', '''InformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys __lowerCamelCase : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
379
1
# Algorithm for the pigeonhole sorting def _SCREAMING_SNAKE_CASE ( lowercase : str ): '''simple docstring''' lowerCamelCase_ = min(lowercase ) # min() finds the minimum value lowerCamelCase_ = max(lowercase ) # max() finds the maximum value lowerCamelCase_ = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size lowerCamelCase_ = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(lowercase , lowercase ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. lowerCamelCase_ = 0 for count in range(lowercase ): while holes[count] > 0: holes[count] -= 1 lowerCamelCase_ = count + min_val i += 1 def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowerCamelCase_ = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(lowercase ) print('Sorted order is:' , ' '.join(lowercase ) ) if __name__ == "__main__": main()
70
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[torch.FloatTensor] = None SCREAMING_SNAKE_CASE_ : torch.FloatTensor = None SCREAMING_SNAKE_CASE_ : Optional[Tuple[torch.FloatTensor]] = None SCREAMING_SNAKE_CASE_ : Optional[Tuple[torch.FloatTensor]] = None class lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' def __init__( self , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__=512 , lowerCAmelCase__="cls" , lowerCAmelCase__=False , lowerCAmelCase__=True , **lowerCAmelCase__ , ) -> Tuple: super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = project_dim SCREAMING_SNAKE_CASE = pooler_fn SCREAMING_SNAKE_CASE = learn_encoder SCREAMING_SNAKE_CASE = use_attention_mask class lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [R"""pooler""", R"""logit_scale"""] SCREAMING_SNAKE_CASE_ : List[Any] = [R"""position_ids""", R"""predictions.decoder.bias"""] SCREAMING_SNAKE_CASE_ : Union[str, Any] = """roberta""" SCREAMING_SNAKE_CASE_ : Dict = RobertaSeriesConfig def __init__( self , lowerCAmelCase__ ) -> Union[str, Any]: super().__init__(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = XLMRobertaModel(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase__ , 'has_pre_transformation' , lowerCAmelCase__ ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def __A ( self , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE = self.base_model( input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , position_ids=lowerCAmelCase__ , head_mask=lowerCAmelCase__ , inputs_embeds=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , encoder_attention_mask=lowerCAmelCase__ , output_attentions=lowerCAmelCase__ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=lowerCAmelCase__ , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE = outputs['hidden_states'][-2] SCREAMING_SNAKE_CASE = self.pre_LN(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = self.transformation_pre(lowerCAmelCase__ ) return TransformationModelOutput( projection_state=lowerCAmelCase__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=lowerCAmelCase__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
247
0
'''simple docstring''' import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _lowerCamelCase ( lowercase : Dict = 3 ) -> List[str]: '''simple docstring''' if isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("number of qubits must be a integer." ) if number_of_qubits <= 0: raise ValueError("number of qubits must be > 0." ) if math.floor(_lowerCamelCase ) != number_of_qubits: raise ValueError("number of qubits must be exact integer." ) if number_of_qubits > 10: raise ValueError("number of qubits too large to simulate(>10)." ) _a = QuantumRegister(_lowerCamelCase , "qr" ) _a = ClassicalRegister(_lowerCamelCase , "cr" ) _a = QuantumCircuit(_lowerCamelCase , _lowerCamelCase ) _a = number_of_qubits for i in range(_lowerCamelCase ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(_lowerCamelCase ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , _lowerCamelCase , _lowerCamelCase ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(_lowerCamelCase , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(_lowerCamelCase , _lowerCamelCase ) # simulate with 10000 shots _a = Aer.get_backend("qasm_simulator" ) _a = execute(_lowerCamelCase , _lowerCamelCase , shots=1_0000 ) return job.result().get_counts(_lowerCamelCase ) if __name__ == "__main__": print( f"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
717
'''simple docstring''' import os from datetime import datetime as dt from github import Github lowerCAmelCase_ : List[Any] = [ 'good first issue', 'feature request', 'wip', ] def _lowerCamelCase ( ) -> Dict: _a = Github(os.environ["GITHUB_TOKEN"] ) _a = g.get_repo("huggingface/accelerate" ) _a = repo.get_issues(state="open" ) for issue in open_issues: _a = sorted([comment for comment in issue.get_comments()] , key=lambda lowercase : i.created_at , reverse=lowercase ) _a = comments[0] if len(lowercase ) > 0 else None _a = dt.utcnow() _a = (current_time - issue.updated_at).days _a = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state="closed" ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) " "are likely to be ignored." ) if __name__ == "__main__": main()
521
0
'''simple docstring''' from __future__ import annotations from PIL import Image # Define glider example __lowerCamelCase = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example __lowerCamelCase = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def UpperCAmelCase__ ( UpperCAmelCase__ ) -> list[list[int]]: A_ = [] for i in range(len(UpperCAmelCase__ ) ): A_ = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours A_ = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(UpperCAmelCase__ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(UpperCAmelCase__ ) - 1: neighbour_count += cells[i + 1][j] if i < len(UpperCAmelCase__ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. A_ = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(UpperCAmelCase__ ) return next_generation def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> list[Image.Image]: A_ = [] for _ in range(UpperCAmelCase__ ): # Create output image A_ = Image.new("""RGB""", (len(cells[0] ), len(UpperCAmelCase__ )) ) A_ = img.load() # Save cells to image for x in range(len(UpperCAmelCase__ ) ): for y in range(len(cells[0] ) ): A_ = 2_55 - cells[y][x] * 2_55 A_ = (colour, colour, colour) # Save image images.append(UpperCAmelCase__ ) A_ = new_generation(UpperCAmelCase__ ) return images if __name__ == "__main__": __lowerCamelCase = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
288
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''', } class A__ ( _snake_case , _snake_case ): lowercase = "resnet" lowercase = ["basic", "bottleneck"] def __init__( self , UpperCamelCase__=3 , UpperCamelCase__=64 , UpperCamelCase__=[256, 512, 1024, 2048] , UpperCamelCase__=[3, 4, 6, 3] , UpperCamelCase__="bottleneck" , UpperCamelCase__="relu" , UpperCamelCase__=False , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ , ) -> List[str]: '''simple docstring''' super().__init__(**UpperCamelCase__ ) if layer_type not in self.layer_types: raise ValueError(f'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) A_ = num_channels A_ = embedding_size A_ = hidden_sizes A_ = depths A_ = layer_type A_ = hidden_act A_ = downsample_in_first_stage A_ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(UpperCamelCase__ ) + 1 )] A_ , A_ = get_aligned_output_features_output_indices( out_features=UpperCamelCase__ , out_indices=UpperCamelCase__ , stage_names=self.stage_names ) class A__ ( _snake_case ): lowercase = version.parse("1.11" ) @property def snake_case_ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def snake_case_ ( self ) -> float: '''simple docstring''' return 1e-3
288
1
"""simple docstring""" import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def __snake_case ( ) -> Any: """simple docstring""" A = 'https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png' A = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ).convert('RGB' ) return image def __snake_case ( UpperCamelCase__ ) -> Any: """simple docstring""" A = [] # fmt: off # vision encoder rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding') ) rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding') ) rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight') ) rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias') ) rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight') ) rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((f'visual_encoder.blocks.{i}.norm1.weight', f'vision_model.encoder.layers.{i}.layer_norm1.weight') ) rename_keys.append((f'visual_encoder.blocks.{i}.norm1.bias', f'vision_model.encoder.layers.{i}.layer_norm1.bias') ) rename_keys.append((f'visual_encoder.blocks.{i}.norm2.weight', f'vision_model.encoder.layers.{i}.layer_norm2.weight') ) rename_keys.append((f'visual_encoder.blocks.{i}.norm2.bias', f'vision_model.encoder.layers.{i}.layer_norm2.bias') ) rename_keys.append((f'visual_encoder.blocks.{i}.attn.qkv.weight', f'vision_model.encoder.layers.{i}.self_attn.qkv.weight') ) rename_keys.append((f'visual_encoder.blocks.{i}.attn.proj.weight', f'vision_model.encoder.layers.{i}.self_attn.projection.weight',) ) rename_keys.append((f'visual_encoder.blocks.{i}.attn.proj.bias', f'vision_model.encoder.layers.{i}.self_attn.projection.bias') ) rename_keys.append((f'visual_encoder.blocks.{i}.mlp.fc1.weight', f'vision_model.encoder.layers.{i}.mlp.fc1.weight') ) rename_keys.append((f'visual_encoder.blocks.{i}.mlp.fc1.bias', f'vision_model.encoder.layers.{i}.mlp.fc1.bias') ) rename_keys.append((f'visual_encoder.blocks.{i}.mlp.fc2.weight', f'vision_model.encoder.layers.{i}.mlp.fc2.weight') ) rename_keys.append((f'visual_encoder.blocks.{i}.mlp.fc2.bias', f'vision_model.encoder.layers.{i}.mlp.fc2.bias') ) # QFormer rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.layernorm.weight') ) rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.layernorm.bias') ) # fmt: on return rename_keys def __snake_case ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: """simple docstring""" A = dct.pop(UpperCamelCase__ ) A = val def __snake_case ( UpperCamelCase__ , UpperCamelCase__ ) -> Dict: """simple docstring""" for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases A = state_dict.pop(f'visual_encoder.blocks.{i}.attn.q_bias' ) A = state_dict.pop(f'visual_encoder.blocks.{i}.attn.v_bias' ) # next, set bias in the state dict A = torch.cat((q_bias, torch.zeros_like(UpperCamelCase__ , requires_grad=UpperCamelCase__ ), v_bias) ) A = qkv_bias def __snake_case ( UpperCamelCase__ , UpperCamelCase__ ) -> str: """simple docstring""" A = 364 if 'coco' in model_name else 224 A = BlipaVisionConfig(image_size=UpperCamelCase__ ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: A = OPTConfig.from_pretrained('facebook/opt-2.7b' , eos_token_id=UpperCamelCase__ ).to_dict() elif "opt-6.7b" in model_name: A = OPTConfig.from_pretrained('facebook/opt-6.7b' , eos_token_id=UpperCamelCase__ ).to_dict() elif "t5-xl" in model_name: A = TaConfig.from_pretrained('google/flan-t5-xl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: A = TaConfig.from_pretrained('google/flan-t5-xxl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() A = BlipaConfig(vision_config=UpperCamelCase__ , text_config=UpperCamelCase__ ) return config, image_size @torch.no_grad() def __snake_case ( UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=False ) -> Tuple: """simple docstring""" A = ( AutoTokenizer.from_pretrained('facebook/opt-2.7b' ) if 'opt' in model_name else AutoTokenizer.from_pretrained('google/flan-t5-xl' ) ) A = tokenizer('\n' , add_special_tokens=UpperCamelCase__ ).input_ids[0] A , A = get_blipa_config(UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) A = BlipaForConditionalGeneration(UpperCamelCase__ ).eval() A = { 'blip2-opt-2.7b': ('blip2_opt', 'pretrain_opt2.7b'), 'blip2-opt-6.7b': ('blip2_opt', 'pretrain_opt6.7b'), 'blip2-opt-2.7b-coco': ('blip2_opt', 'caption_coco_opt2.7b'), 'blip2-opt-6.7b-coco': ('blip2_opt', 'caption_coco_opt6.7b'), 'blip2-flan-t5-xl': ('blip2_t5', 'pretrain_flant5xl'), 'blip2-flan-t5-xl-coco': ('blip2_t5', 'caption_coco_flant5xl'), 'blip2-flan-t5-xxl': ('blip2_t5', 'pretrain_flant5xxl'), } A , A = model_name_to_original[model_name] # load original model print('Loading original model...' ) A = 'cuda' if torch.cuda.is_available() else 'cpu' A , A , A = load_model_and_preprocess( name=UpperCamelCase__ , model_type=UpperCamelCase__ , is_eval=UpperCamelCase__ , device=UpperCamelCase__ ) original_model.eval() print('Done!' ) # update state dict keys A = original_model.state_dict() A = create_rename_keys(UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): A = state_dict.pop(UpperCamelCase__ ) if key.startswith('Qformer.bert' ): A = key.replace('Qformer.bert' , 'qformer' ) if "attention.self" in key: A = key.replace('self' , 'attention' ) if "opt_proj" in key: A = key.replace('opt_proj' , 'language_projection' ) if "t5_proj" in key: A = key.replace('t5_proj' , 'language_projection' ) if key.startswith('opt' ): A = key.replace('opt' , 'language' ) if key.startswith('t5' ): A = key.replace('t5' , 'language' ) A = val # read in qv biases read_in_q_v_bias(UpperCamelCase__ , UpperCamelCase__ ) A , A = hf_model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) assert len(UpperCamelCase__ ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] A = load_demo_image() A = vis_processors['eval'](UpperCamelCase__ ).unsqueeze(0 ).to(UpperCamelCase__ ) A = tokenizer(['\n'] , return_tensors='pt' ).input_ids.to(UpperCamelCase__ ) # create processor A = BlipImageProcessor( size={'height': image_size, 'width': image_size} , image_mean=UpperCamelCase__ , image_std=UpperCamelCase__ ) A = BlipaProcessor(image_processor=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) A = processor(images=UpperCamelCase__ , return_tensors='pt' ).pixel_values.to(UpperCamelCase__ ) # make sure processor creates exact same pixel values assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ ) original_model.to(UpperCamelCase__ ) hf_model.to(UpperCamelCase__ ) with torch.no_grad(): if "opt" in model_name: A = original_model({'image': original_pixel_values, 'text_input': ['']} ).logits A = hf_model(UpperCamelCase__ , UpperCamelCase__ ).logits else: A = original_model( {'image': original_pixel_values, 'text_input': ['\n'], 'text_output': ['\n']} ).logits A = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) A = hf_model(UpperCamelCase__ , UpperCamelCase__ , labels=UpperCamelCase__ ).logits assert original_logits.shape == logits.shape print('First values of original logits:' , original_logits[0, :3, :3] ) print('First values of HF logits:' , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": A = torch.tensor( [[-41.5850, -4.4_4_4_0, -8.9_9_2_2], [-47.4322, -5.9_1_4_3, -1.7_3_4_0]] , device=UpperCamelCase__ ) assert torch.allclose(logits[0, :3, :3] , UpperCamelCase__ , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": A = torch.tensor( [[-57.0109, -9.8_9_6_7, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=UpperCamelCase__ ) else: # cast to same type A = logits.dtype assert torch.allclose(original_logits.to(UpperCamelCase__ ) , UpperCamelCase__ , atol=1E-2 ) print('Looks ok!' ) print('Generating a caption...' ) A = '' A = tokenizer(UpperCamelCase__ , return_tensors='pt' ).input_ids.to(UpperCamelCase__ ) A = original_model.generate({'image': original_pixel_values} ) A = hf_model.generate( UpperCamelCase__ , UpperCamelCase__ , do_sample=UpperCamelCase__ , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print('Original generation:' , UpperCamelCase__ ) A = input_ids.shape[1] A = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=UpperCamelCase__ ) A = [text.strip() for text in output_text] print('HF generation:' , UpperCamelCase__ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(UpperCamelCase__ ) hf_model.save_pretrained(UpperCamelCase__ ) if push_to_hub: processor.push_to_hub(f'nielsr/{model_name}' ) hf_model.push_to_hub(f'nielsr/{model_name}' ) if __name__ == "__main__": UpperCamelCase : Optional[int] = argparse.ArgumentParser() UpperCamelCase : str = [ "blip2-opt-2.7b", "blip2-opt-6.7b", "blip2-opt-2.7b-coco", "blip2-opt-6.7b-coco", "blip2-flan-t5-xl", "blip2-flan-t5-xl-coco", "blip2-flan-t5-xxl", ] parser.add_argument( "--model_name", default="blip2-opt-2.7b", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) UpperCamelCase : str = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
716
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class lowerCamelCase__ ( unittest.TestCase ): lowerCAmelCase = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def __a ( self : Dict , _lowercase : int , _lowercase : Any , _lowercase : int ): A = hf_hub_download( repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) A = VideoClassificationPipeline(model=_lowercase , image_processor=_lowercase , top_k=2 ) A = [ example_video_filepath, 'https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4', ] return video_classifier, examples def __a ( self : Tuple , _lowercase : Union[str, Any] , _lowercase : List[Any] ): for example in examples: A = video_classifier(_lowercase ) self.assertEqual( _lowercase , [ {'score': ANY(_lowercase ), 'label': ANY(_lowercase )}, {'score': ANY(_lowercase ), 'label': ANY(_lowercase )}, ] , ) @require_torch def __a ( self : str ): A = 'hf-internal-testing/tiny-random-VideoMAEForVideoClassification' A = VideoMAEFeatureExtractor( size={'shortest_edge': 10} , crop_size={'height': 10, 'width': 10} ) A = pipeline( 'video-classification' , model=_lowercase , feature_extractor=_lowercase , frame_sampling_rate=4 ) A = hf_hub_download(repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) A = video_classifier(_lowercase , top_k=2 ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}] , ) A = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}], [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}], ] , ) @require_tf def __a ( self : Dict ): pass
91
0
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class __lowerCAmelCase (__UpperCamelCase ): '''simple docstring''' def __init__( self , a , a=None , a=None , a=0 ): """simple docstring""" snake_case_ :Union[str, Any] = 1.0 if scale is None else scale snake_case_ :List[str] = 0.0 if loc is None else loc super().__init__(a , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=a )] ) @property def _a ( self ): """simple docstring""" return self.base_dist.mean * self.scale + self.loc @property def _a ( self ): """simple docstring""" return self.base_dist.variance * self.scale**2 @property def _a ( self ): """simple docstring""" return self.variance.sqrt() class __lowerCAmelCase (nn.Module ): '''simple docstring''' def __init__( self , a , a , a , **a ): """simple docstring""" super().__init__(**a ) snake_case_ :Union[str, Any] = args_dim snake_case_ :Union[str, Any] = nn.ModuleList([nn.Linear(a , a ) for dim in args_dim.values()] ) snake_case_ :Optional[Any] = domain_map def _a ( self , a ): """simple docstring""" snake_case_ :Dict = [proj(a ) for proj in self.proj] return self.domain_map(*a ) class __lowerCAmelCase (nn.Module ): '''simple docstring''' def __init__( self , a ): """simple docstring""" super().__init__() snake_case_ :Optional[Any] = function def _a ( self , a , *a ): """simple docstring""" return self.function(a , *a ) class __lowerCAmelCase : '''simple docstring''' a__ = 42 a__ = 42 a__ = 42 def __init__( self , a = 1 ): """simple docstring""" snake_case_ :Optional[int] = dim snake_case_ :Dict = {k: dim * self.args_dim[k] for k in self.args_dim} def _a ( self , a ): """simple docstring""" if self.dim == 1: return self.distribution_class(*a ) else: return Independent(self.distribution_class(*a ) , 1 ) def _a ( self , a , a = None , a = None , ): """simple docstring""" snake_case_ :int = self._base_distribution(a ) if loc is None and scale is None: return distr else: return AffineTransformed(a , loc=a , scale=a , event_dim=self.event_dim ) @property def _a ( self ): """simple docstring""" return () if self.dim == 1 else (self.dim,) @property def _a ( self ): """simple docstring""" return len(self.event_shape ) @property def _a ( self ): """simple docstring""" return 0.0 def _a ( self , a ): """simple docstring""" return ParameterProjection( in_features=a , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def _a ( self , *a ): """simple docstring""" raise NotImplementedError() @staticmethod def _a ( a ): """simple docstring""" return (x + torch.sqrt(torch.square(a ) + 4.0 )) / 2.0 class __lowerCAmelCase (__UpperCamelCase ): '''simple docstring''' a__ = {"df": 1, "loc": 1, "scale": 1} a__ = StudentT @classmethod def _a ( cls , a , a , a ): """simple docstring""" snake_case_ :Optional[int] = cls.squareplus(a ).clamp_min(torch.finfo(scale.dtype ).eps ) snake_case_ :int = 2.0 + cls.squareplus(a ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class __lowerCAmelCase (__UpperCamelCase ): '''simple docstring''' a__ = {"loc": 1, "scale": 1} a__ = Normal @classmethod def _a ( cls , a , a ): """simple docstring""" snake_case_ :Optional[int] = cls.squareplus(a ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class __lowerCAmelCase (__UpperCamelCase ): '''simple docstring''' a__ = {"total_count": 1, "logits": 1} a__ = NegativeBinomial @classmethod def _a ( cls , a , a ): """simple docstring""" snake_case_ :Tuple = cls.squareplus(a ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def _a ( self , a ): """simple docstring""" snake_case_ , snake_case_ :Any = distr_args if self.dim == 1: return self.distribution_class(total_count=a , logits=a ) else: return Independent(self.distribution_class(total_count=a , logits=a ) , 1 ) def _a ( self , a , a = None , a = None ): """simple docstring""" snake_case_ , snake_case_ :Optional[Any] = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
584
"""simple docstring""" __UpperCAmelCase : List[str] = {str(digit): digit**5 for digit in range(10)} def A ( _A ): """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(_A ) ) def A ( ): """simple docstring""" return sum( number for number in range(1_000, 1_000_000 ) if number == digits_fifth_powers_sum(_A ) ) if __name__ == "__main__": print(solution())
584
1
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class __SCREAMING_SNAKE_CASE ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE : Union[str, Any] = IFPipeline __SCREAMING_SNAKE_CASE : Optional[Any] = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} __SCREAMING_SNAKE_CASE : List[str] = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : int = PipelineTesterMixin.required_optional_params - {"""latents"""} def UpperCAmelCase__ ( self : Tuple ): return self._get_dummy_components() def UpperCAmelCase__ ( self : List[str] , __UpperCamelCase : Any , __UpperCamelCase : Optional[int]=0 ): if str(__UpperCamelCase ).startswith("mps" ): _UpperCAmelCase = torch.manual_seed(__UpperCamelCase ) else: _UpperCAmelCase = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) _UpperCAmelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase__ ( self : List[str] ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def UpperCAmelCase__ ( self : Union[str, Any] ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def UpperCAmelCase__ ( self : List[str] ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def UpperCAmelCase__ ( self : Tuple ): self._test_save_load_local() def UpperCAmelCase__ ( self : Union[str, Any] ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def UpperCAmelCase__ ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase): def UpperCAmelCase__ ( self : Optional[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Optional[Any] ): # if _UpperCAmelCase = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0" , variant="fp16" , torch_dtype=torch.floataa ) _UpperCAmelCase = IFSuperResolutionPipeline.from_pretrained( "DeepFloyd/IF-II-L-v1.0" , variant="fp16" , torch_dtype=torch.floataa , text_encoder=__UpperCamelCase , tokenizer=__UpperCamelCase ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("cuda" ) _UpperCAmelCase = pipe_a.encode_prompt("anime turtle" , device="cuda" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() _UpperCAmelCase = None _UpperCAmelCase = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img _UpperCAmelCase = IFImgaImgPipeline(**pipe_a.components ) _UpperCAmelCase = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting _UpperCAmelCase = IFInpaintingPipeline(**pipe_a.components ) _UpperCAmelCase = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : List[str] , __UpperCamelCase : Optional[int] ): # pipeline 1 _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCAmelCase = pipe_a( prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , num_inference_steps=2 , generator=__UpperCamelCase , output_type="np" , ) _UpperCAmelCase = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 _UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy" ) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCamelCase ) _UpperCAmelCase = pipe_a( prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , image=__UpperCamelCase , generator=__UpperCamelCase , num_inference_steps=2 , output_type="np" , ) _UpperCAmelCase = output.images[0] assert image.shape == (256, 256, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy" ) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase ) def UpperCAmelCase__ ( self : List[str] , __UpperCamelCase : Tuple , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : str , __UpperCamelCase : Union[str, Any] ): # pipeline 1 _start_torch_memory_measurement() _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCamelCase ) _UpperCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCAmelCase = pipe_a( prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , image=__UpperCamelCase , num_inference_steps=2 , generator=__UpperCamelCase , output_type="np" , ) _UpperCAmelCase = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy" ) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCAmelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__UpperCamelCase ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCamelCase ) _UpperCAmelCase = pipe_a( prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , image=__UpperCamelCase , original_image=__UpperCamelCase , generator=__UpperCamelCase , num_inference_steps=2 , output_type="np" , ) _UpperCAmelCase = output.images[0] assert image.shape == (256, 256, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy" ) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase ) def UpperCAmelCase__ ( self : str , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Any , __UpperCamelCase : Optional[int] ): # pipeline 1 _start_torch_memory_measurement() _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCamelCase ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(__UpperCamelCase ) _UpperCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCAmelCase = pipe_a( prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , image=__UpperCamelCase , mask_image=__UpperCamelCase , num_inference_steps=2 , generator=__UpperCamelCase , output_type="np" , ) _UpperCAmelCase = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy" ) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCamelCase ) _UpperCAmelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__UpperCamelCase ) _UpperCAmelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(__UpperCamelCase ) _UpperCAmelCase = pipe_a( prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , image=__UpperCamelCase , mask_image=__UpperCamelCase , original_image=__UpperCamelCase , generator=__UpperCamelCase , num_inference_steps=2 , output_type="np" , ) _UpperCAmelCase = output.images[0] assert image.shape == (256, 256, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy" ) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase ) def __lowerCamelCase ( ) -> List[str]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
719
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig __lowerCAmelCase = [ "openmmlab/upernet-convnext-tiny", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring __lowerCAmelCase = "UperNetConfig" class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Dict , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : Union[int, Tuple[int, int]] , __UpperCamelCase : Union[int, Tuple[int, int], str] = 0 , __UpperCamelCase : bool = False , __UpperCamelCase : Union[int, Tuple[int, int]] = 1 , ): super().__init__() _UpperCAmelCase = nn.Convad( in_channels=__UpperCamelCase , out_channels=__UpperCamelCase , kernel_size=__UpperCamelCase , padding=__UpperCamelCase , bias=__UpperCamelCase , dilation=__UpperCamelCase , ) _UpperCAmelCase = nn.BatchNormad(__UpperCamelCase ) _UpperCAmelCase = nn.ReLU() def UpperCAmelCase__ ( self : Tuple , __UpperCamelCase : torch.Tensor ): _UpperCAmelCase = self.conv(__UpperCamelCase ) _UpperCAmelCase = self.batch_norm(__UpperCamelCase ) _UpperCAmelCase = self.activation(__UpperCamelCase ) return output class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : str , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : int ): super().__init__() _UpperCAmelCase = [ nn.AdaptiveAvgPoolad(__UpperCamelCase ), UperNetConvModule(__UpperCamelCase , __UpperCamelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(__UpperCamelCase ) , __UpperCamelCase ) def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : torch.Tensor ): _UpperCAmelCase = input for layer in self.layers: _UpperCAmelCase = layer(__UpperCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Dict , __UpperCamelCase : Tuple[int, ...] , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : bool ): super().__init__() _UpperCAmelCase = pool_scales _UpperCAmelCase = align_corners _UpperCAmelCase = in_channels _UpperCAmelCase = channels _UpperCAmelCase = [] for i, pool_scale in enumerate(__UpperCamelCase ): _UpperCAmelCase = UperNetPyramidPoolingBlock(pool_scale=__UpperCamelCase , in_channels=__UpperCamelCase , channels=__UpperCamelCase ) self.blocks.append(__UpperCamelCase ) self.add_module(str(__UpperCamelCase ) , __UpperCamelCase ) def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : torch.Tensor ): _UpperCAmelCase = [] for ppm in self.blocks: _UpperCAmelCase = ppm(__UpperCamelCase ) _UpperCAmelCase = nn.functional.interpolate( __UpperCamelCase , size=x.size()[2:] , mode="bilinear" , align_corners=self.align_corners ) ppm_outs.append(__UpperCamelCase ) return ppm_outs class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Tuple , __UpperCamelCase : int , __UpperCamelCase : Tuple ): super().__init__() _UpperCAmelCase = config _UpperCAmelCase = config.pool_scales # e.g. (1, 2, 3, 6) _UpperCAmelCase = in_channels _UpperCAmelCase = config.hidden_size _UpperCAmelCase = False _UpperCAmelCase = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module _UpperCAmelCase = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) _UpperCAmelCase = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module _UpperCAmelCase = nn.ModuleList() _UpperCAmelCase = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer _UpperCAmelCase = UperNetConvModule(__UpperCamelCase , self.channels , kernel_size=1 ) _UpperCAmelCase = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(__UpperCamelCase ) self.fpn_convs.append(__UpperCamelCase ) _UpperCAmelCase = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def UpperCAmelCase__ ( self : str ): self.apply(self._init_weights ) def UpperCAmelCase__ ( self : Optional[int] , __UpperCamelCase : str ): if isinstance(__UpperCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase__ ( self : Dict , __UpperCamelCase : Union[str, Any] ): _UpperCAmelCase = inputs[-1] _UpperCAmelCase = [x] psp_outs.extend(self.psp_modules(__UpperCamelCase ) ) _UpperCAmelCase = torch.cat(__UpperCamelCase , dim=1 ) _UpperCAmelCase = self.bottleneck(__UpperCamelCase ) return output def UpperCAmelCase__ ( self : Any , __UpperCamelCase : torch.Tensor ): # build laterals _UpperCAmelCase = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(__UpperCamelCase ) ) # build top-down path _UpperCAmelCase = len(__UpperCamelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): _UpperCAmelCase = laterals[i - 1].shape[2:] _UpperCAmelCase = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=__UpperCamelCase , mode="bilinear" , align_corners=self.align_corners ) # build outputs _UpperCAmelCase = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): _UpperCAmelCase = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) _UpperCAmelCase = torch.cat(__UpperCamelCase , dim=1 ) _UpperCAmelCase = self.fpn_bottleneck(__UpperCamelCase ) _UpperCAmelCase = self.classifier(__UpperCamelCase ) return output class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Dict , __UpperCamelCase : str , __UpperCamelCase : int = 2 , __UpperCamelCase : int = 3 , __UpperCamelCase : Union[int, Tuple[int, int]] = 1 ): super().__init__() _UpperCAmelCase = config _UpperCAmelCase = config.auxiliary_in_channels _UpperCAmelCase = config.auxiliary_channels _UpperCAmelCase = config.auxiliary_num_convs _UpperCAmelCase = config.auxiliary_concat_input _UpperCAmelCase = in_index _UpperCAmelCase = (kernel_size // 2) * dilation _UpperCAmelCase = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=__UpperCamelCase , padding=__UpperCamelCase , dilation=__UpperCamelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=__UpperCamelCase , padding=__UpperCamelCase , dilation=__UpperCamelCase ) ) if self.num_convs == 0: _UpperCAmelCase = nn.Identity() else: _UpperCAmelCase = nn.Sequential(*__UpperCamelCase ) if self.concat_input: _UpperCAmelCase = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=__UpperCamelCase , padding=kernel_size // 2 ) _UpperCAmelCase = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def UpperCAmelCase__ ( self : List[Any] ): self.apply(self._init_weights ) def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : Optional[Any] ): if isinstance(__UpperCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : torch.Tensor ): # just take the relevant feature maps _UpperCAmelCase = encoder_hidden_states[self.in_index] _UpperCAmelCase = self.convs(__UpperCamelCase ) if self.concat_input: _UpperCAmelCase = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) _UpperCAmelCase = self.classifier(__UpperCamelCase ) return output class __SCREAMING_SNAKE_CASE ( lowercase): __SCREAMING_SNAKE_CASE : Dict = UperNetConfig __SCREAMING_SNAKE_CASE : str = """pixel_values""" __SCREAMING_SNAKE_CASE : str = True def UpperCAmelCase__ ( self : Tuple , __UpperCamelCase : int ): if isinstance(__UpperCamelCase , __UpperCamelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def UpperCAmelCase__ ( self : Union[str, Any] ): self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def UpperCAmelCase__ ( self : Dict , __UpperCamelCase : Tuple , __UpperCamelCase : Tuple=False ): if isinstance(__UpperCamelCase , __UpperCamelCase ): _UpperCAmelCase = value __lowerCAmelCase = r"\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __lowerCAmelCase = r"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( """UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.""" , lowercase , ) class __SCREAMING_SNAKE_CASE ( lowercase): def __init__( self : Optional[int] , __UpperCamelCase : str ): super().__init__(__UpperCamelCase ) _UpperCAmelCase = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) _UpperCAmelCase = UperNetHead(__UpperCamelCase , in_channels=self.backbone.channels ) _UpperCAmelCase = UperNetFCNHead(__UpperCamelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length" ) ) @replace_return_docstrings(output_type=__UpperCamelCase , config_class=_CONFIG_FOR_DOC ) def UpperCAmelCase__ ( self : Dict , __UpperCamelCase : Optional[torch.Tensor] = None , __UpperCamelCase : Optional[bool] = None , __UpperCamelCase : Optional[bool] = None , __UpperCamelCase : Optional[torch.Tensor] = None , __UpperCamelCase : Optional[bool] = None , ): _UpperCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCAmelCase = output_attentions if output_attentions is not None else self.config.output_attentions _UpperCAmelCase = self.backbone.forward_with_filtered_kwargs( __UpperCamelCase , output_hidden_states=__UpperCamelCase , output_attentions=__UpperCamelCase ) _UpperCAmelCase = outputs.feature_maps _UpperCAmelCase = self.decode_head(__UpperCamelCase ) _UpperCAmelCase = nn.functional.interpolate(__UpperCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=__UpperCamelCase ) _UpperCAmelCase = None if self.auxiliary_head is not None: _UpperCAmelCase = self.auxiliary_head(__UpperCamelCase ) _UpperCAmelCase = nn.functional.interpolate( __UpperCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=__UpperCamelCase ) _UpperCAmelCase = None if labels is not None: if self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one" ) else: # compute weighted loss _UpperCAmelCase = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) _UpperCAmelCase = loss_fct(__UpperCamelCase , __UpperCamelCase ) _UpperCAmelCase = loss_fct(__UpperCamelCase , __UpperCamelCase ) _UpperCAmelCase = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: _UpperCAmelCase = (logits,) + outputs[1:] else: _UpperCAmelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=__UpperCamelCase , logits=__UpperCamelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
129
0
import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput snake_case_ = '''scheduler_config.json''' class SCREAMING_SNAKE_CASE__ (_UpperCAmelCase ): __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Tuple = 2 __lowerCamelCase : Dict = 3 __lowerCamelCase : str = 4 __lowerCamelCase : Optional[int] = 5 __lowerCamelCase : Any = 6 __lowerCamelCase : int = 7 __lowerCamelCase : Any = 8 __lowerCamelCase : List[Any] = 9 __lowerCamelCase : Any = 10 __lowerCamelCase : List[str] = 11 __lowerCamelCase : Optional[int] = 12 __lowerCamelCase : Any = 13 __lowerCamelCase : Dict = 14 @dataclass class SCREAMING_SNAKE_CASE__ (_UpperCAmelCase ): __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE__ : __lowerCamelCase : Dict = SCHEDULER_CONFIG_NAME __lowerCamelCase : List[str] = [] __lowerCamelCase : Optional[int] = True @classmethod def snake_case_ ( cls , a = None , a = None , a=False , **a , ): lowercase__ , lowercase__ , lowercase__ : List[str] = cls.load_config( pretrained_model_name_or_path=__UpperCamelCase , subfolder=__UpperCamelCase , return_unused_kwargs=__UpperCamelCase , return_commit_hash=__UpperCamelCase , **__UpperCamelCase , ) return cls.from_config(__UpperCamelCase , return_unused_kwargs=__UpperCamelCase , **__UpperCamelCase) def snake_case_ ( self , a , a = False , **a): self.save_config(save_directory=__UpperCamelCase , push_to_hub=__UpperCamelCase , **__UpperCamelCase) @property def snake_case_ ( self): return self._get_compatibles() @classmethod def snake_case_ ( cls): lowercase__ : List[str] = list(set([cls.__name__] + cls._compatibles)) lowercase__ : List[str] = importlib.import_module(__name__.split('.')[0]) lowercase__ : int = [ getattr(__UpperCamelCase , __UpperCamelCase) for c in compatible_classes_str if hasattr(__UpperCamelCase , __UpperCamelCase) ] return compatible_classes
164
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig a : List[str] = logging.get_logger(__name__) class a_ : def __init__( self : List[str] , __UpperCamelCase : Any , __UpperCamelCase : Tuple ) ->Tuple: '''simple docstring''' _UpperCAmelCase = question_encoder _UpperCAmelCase = generator _UpperCAmelCase = self.question_encoder def _snake_case ( self : int , __UpperCamelCase : str ) ->Dict: '''simple docstring''' if os.path.isfile(__UpperCamelCase ): raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) _UpperCAmelCase = os.path.join(__UpperCamelCase , """question_encoder_tokenizer""" ) _UpperCAmelCase = os.path.join(__UpperCamelCase , """generator_tokenizer""" ) self.question_encoder.save_pretrained(__UpperCamelCase ) self.generator.save_pretrained(__UpperCamelCase ) @classmethod def _snake_case ( cls : Optional[Any] , __UpperCamelCase : Tuple , **__UpperCamelCase : Optional[Any] ) ->Tuple: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer _UpperCAmelCase = kwargs.pop("""config""" , __UpperCamelCase ) if config is None: _UpperCAmelCase = RagConfig.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = AutoTokenizer.from_pretrained( __UpperCamelCase , config=config.question_encoder , subfolder="""question_encoder_tokenizer""" ) _UpperCAmelCase = AutoTokenizer.from_pretrained( __UpperCamelCase , config=config.generator , subfolder="""generator_tokenizer""" ) return cls(question_encoder=__UpperCamelCase , generator=__UpperCamelCase ) def __call__( self : Any , *__UpperCamelCase : List[Any] , **__UpperCamelCase : Optional[Any] ) ->Optional[Any]: '''simple docstring''' return self.current_tokenizer(*__UpperCamelCase , **__UpperCamelCase ) def _snake_case ( self : Union[str, Any] , *__UpperCamelCase : List[Any] , **__UpperCamelCase : Tuple ) ->Any: '''simple docstring''' return self.generator.batch_decode(*__UpperCamelCase , **__UpperCamelCase ) def _snake_case ( self : Optional[int] , *__UpperCamelCase : Optional[int] , **__UpperCamelCase : List[str] ) ->Union[str, Any]: '''simple docstring''' return self.generator.decode(*__UpperCamelCase , **__UpperCamelCase ) def _snake_case ( self : Union[str, Any] ) ->Dict: '''simple docstring''' _UpperCAmelCase = self.question_encoder def _snake_case ( self : Tuple ) ->Optional[int]: '''simple docstring''' _UpperCAmelCase = self.generator def _snake_case ( self : List[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : Optional[List[str]] = None , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : str = "longest" , __UpperCamelCase : str = None , __UpperCamelCase : bool = True , **__UpperCamelCase : Tuple , ) ->BatchEncoding: '''simple docstring''' warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , __UpperCamelCase , ) if max_length is None: _UpperCAmelCase = self.current_tokenizer.model_max_length _UpperCAmelCase = self( __UpperCamelCase , add_special_tokens=__UpperCamelCase , return_tensors=__UpperCamelCase , max_length=__UpperCamelCase , padding=__UpperCamelCase , truncation=__UpperCamelCase , **__UpperCamelCase , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: _UpperCAmelCase = self.current_tokenizer.model_max_length _UpperCAmelCase = self( text_target=__UpperCamelCase , add_special_tokens=__UpperCamelCase , return_tensors=__UpperCamelCase , padding=__UpperCamelCase , max_length=__UpperCamelCase , truncation=__UpperCamelCase , **__UpperCamelCase , ) _UpperCAmelCase = labels["""input_ids"""] return model_inputs
555
0
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) lowercase_ : List[str] = logging.getLogger(__name__) class lowercase ( a_ ): """simple docstring""" def __UpperCAmelCase ( self : Optional[Any] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : Optional[int]=None ): '''simple docstring''' _snake_case : List[Any] = self.layer[current_layer](lowerCamelCase_ , lowerCamelCase_ , head_mask[current_layer] ) _snake_case : Union[str, Any] = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." , a_ , ) class lowercase ( a_ ): """simple docstring""" def __init__( self : int , lowerCamelCase_ : str ): '''simple docstring''' super().__init__(lowerCamelCase_ ) _snake_case : List[str] = BertEncoderWithPabee(lowerCamelCase_ ) self.init_weights() _snake_case : Tuple = 0 _snake_case : List[str] = 0 _snake_case : Dict = 0 _snake_case : Optional[int] = 0 def __UpperCAmelCase ( self : List[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' _snake_case : Optional[Any] = threshold def __UpperCAmelCase ( self : Any , lowerCamelCase_ : int ): '''simple docstring''' _snake_case : Dict = patience def __UpperCAmelCase ( self : Optional[Any] ): '''simple docstring''' _snake_case : List[Any] = 0 _snake_case : str = 0 def __UpperCAmelCase ( self : Dict ): '''simple docstring''' _snake_case : Tuple = self.inference_layers_num / self.inference_instances_num _snake_case : str = ( f'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =''' f''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***''' ) print(lowerCamelCase_ ) @add_start_docstrings_to_model_forward(lowerCamelCase_ ) def __UpperCAmelCase ( self : List[Any] , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict=None , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : Union[str, Any]=None , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : Dict=None , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : str=None , lowerCamelCase_ : Tuple=False , ): '''simple docstring''' if input_ids is not None and inputs_embeds is not None: raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time' ) elif input_ids is not None: _snake_case : List[str] = input_ids.size() elif inputs_embeds is not None: _snake_case : Optional[int] = inputs_embeds.size()[:-1] else: raise ValueError('You have to specify either input_ids or inputs_embeds' ) _snake_case : List[str] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _snake_case : List[Any] = torch.ones(lowerCamelCase_ , device=lowerCamelCase_ ) if token_type_ids is None: _snake_case : Optional[int] = torch.zeros(lowerCamelCase_ , dtype=torch.long , device=lowerCamelCase_ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _snake_case : torch.Tensor = self.get_extended_attention_mask(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: _snake_case , _snake_case , _snake_case : Tuple = encoder_hidden_states.size() _snake_case : List[str] = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: _snake_case : Dict = torch.ones(lowerCamelCase_ , device=lowerCamelCase_ ) _snake_case : int = self.invert_attention_mask(lowerCamelCase_ ) else: _snake_case : str = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _snake_case : Any = self.get_head_mask(lowerCamelCase_ , self.config.num_hidden_layers ) _snake_case : Dict = self.embeddings( input_ids=lowerCamelCase_ , position_ids=lowerCamelCase_ , token_type_ids=lowerCamelCase_ , inputs_embeds=lowerCamelCase_ ) _snake_case : List[Any] = embedding_output if self.training: _snake_case : int = [] for i in range(self.config.num_hidden_layers ): _snake_case : Tuple = self.encoder.adaptive_forward( lowerCamelCase_ , current_layer=lowerCamelCase_ , attention_mask=lowerCamelCase_ , head_mask=lowerCamelCase_ ) _snake_case : int = self.pooler(lowerCamelCase_ ) _snake_case : List[str] = output_layers[i](output_dropout(lowerCamelCase_ ) ) res.append(lowerCamelCase_ ) elif self.patience == 0: # Use all layers for inference _snake_case : Union[str, Any] = self.encoder( lowerCamelCase_ , attention_mask=lowerCamelCase_ , head_mask=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , encoder_attention_mask=lowerCamelCase_ , ) _snake_case : int = self.pooler(encoder_outputs[0] ) _snake_case : str = [output_layers[self.config.num_hidden_layers - 1](lowerCamelCase_ )] else: _snake_case : Dict = 0 _snake_case : Optional[int] = None _snake_case : Union[str, Any] = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 _snake_case : List[str] = self.encoder.adaptive_forward( lowerCamelCase_ , current_layer=lowerCamelCase_ , attention_mask=lowerCamelCase_ , head_mask=lowerCamelCase_ ) _snake_case : List[str] = self.pooler(lowerCamelCase_ ) _snake_case : Dict = output_layers[i](lowerCamelCase_ ) if regression: _snake_case : Union[str, Any] = logits.detach() if patient_result is not None: _snake_case : Union[str, Any] = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: _snake_case : int = 0 else: _snake_case : Optional[Any] = logits.detach().argmax(dim=1 ) if patient_result is not None: _snake_case : Optional[int] = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(lowerCamelCase_ ) ): patient_counter += 1 else: _snake_case : Optional[int] = 0 _snake_case : Dict = logits if patient_counter == self.patience: break _snake_case : Any = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " , a_ , ) class lowercase ( a_ ): """simple docstring""" def __init__( self : Union[str, Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' super().__init__(lowerCamelCase_ ) _snake_case : List[str] = config.num_labels _snake_case : List[Any] = BertModelWithPabee(lowerCamelCase_ ) _snake_case : List[str] = nn.Dropout(config.hidden_dropout_prob ) _snake_case : Optional[int] = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(lowerCamelCase_ ) def __UpperCAmelCase ( self : Optional[Any] , lowerCamelCase_ : Optional[Any]=None , lowerCamelCase_ : int=None , lowerCamelCase_ : Optional[Any]=None , lowerCamelCase_ : Any=None , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : List[str]=None , ): '''simple docstring''' _snake_case : Tuple = self.bert( input_ids=lowerCamelCase_ , attention_mask=lowerCamelCase_ , token_type_ids=lowerCamelCase_ , position_ids=lowerCamelCase_ , head_mask=lowerCamelCase_ , inputs_embeds=lowerCamelCase_ , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) _snake_case : int = (logits[-1],) if labels is not None: _snake_case : Dict = None _snake_case : Optional[Any] = 0 for ix, logits_item in enumerate(lowerCamelCase_ ): if self.num_labels == 1: # We are doing regression _snake_case : int = MSELoss() _snake_case : Optional[int] = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: _snake_case : str = CrossEntropyLoss() _snake_case : Any = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: _snake_case : List[str] = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 _snake_case : Optional[int] = (total_loss / total_weights,) + outputs return outputs
652
lowercase_ : Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' lowercase_ : Optional[int] = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] lowercase_ : str = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
652
1
import functools def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' snake_case_ = len(__snake_case ) snake_case_ = len(__snake_case ) @functools.cache def min_distance(UpperCamelCase__ , UpperCamelCase__ ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa snake_case_ = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , __snake_case ) , 1 + min_distance(__snake_case , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
362
"""simple docstring""" # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration _A : Dict = """facebook/wmt19-en-de""" _A : str = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model _A : List[Any] = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) _A : int = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test _A : Dict = tokenizer(["""Making tiny model"""], return_tensors="""pt""") _A : List[Any] = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save _A : List[Any] = """tiny-wmt19-en-de""" tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-de
361
0
from collections.abc import Callable import numpy as np def __UpperCamelCase ( a, a, a, a, a) ->np.ndarray: lowerCamelCase__ = int(np.ceil((x_end - xa) / step_size)) lowerCamelCase__ = np.zeros((n + 1,)) lowerCamelCase__ = ya lowerCamelCase__ = xa for k in range(a): lowerCamelCase__ = y[k] + step_size * ode_func(a, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
360
def __UpperCamelCase ( a = 100) ->int: lowerCamelCase__ = (n * (n + 1) // 2) ** 2 lowerCamelCase__ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"""{solution() = }""")
360
1
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def lowercase ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowercase ( self : str ): _snake_case = 1 _snake_case = 3 _snake_case = (32, 32) _snake_case = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_lowerCamelCase ) return image @property def lowercase ( self : int ): torch.manual_seed(0 ) _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 , ) return model @property def lowercase ( self : Tuple ): torch.manual_seed(0 ) _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 , ) return model @property def lowercase ( self : Union[str, Any] ): torch.manual_seed(0 ) _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 , ) return CLIPTextModel(_lowerCamelCase ) @property def lowercase ( self : Optional[Any] ): def extract(*_lowerCamelCase : str , **_lowerCamelCase : str ): class lowerCAmelCase__ : def __init__( self : List[str] ): _snake_case = torch.ones([0] ) def lowercase ( self : Any , _lowerCamelCase : Dict ): self.pixel_values.to(_lowerCamelCase ) return self return Out() return extract def lowercase ( self : Tuple ): _snake_case = '''cpu''' # ensure determinism for the device-dependent torch.Generator _snake_case = self.dummy_cond_unet _snake_case = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) _snake_case = self.dummy_vae _snake_case = self.dummy_text_encoder _snake_case = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # make sure here that pndm scheduler skips prk _snake_case = StableDiffusionPipeline( unet=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , safety_checker=_lowerCamelCase , feature_extractor=self.dummy_extractor , ) _snake_case = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = '''A painting of a squirrel eating a burger''' _snake_case = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) _snake_case = sd_pipe([prompt] , generator=_lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' ) _snake_case = output.images _snake_case = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , return_dict=_lowerCamelCase , )[0] _snake_case = image[0, -3:, -3:, -1] _snake_case = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self : Optional[int] ): _snake_case = '''cpu''' # ensure determinism for the device-dependent torch.Generator _snake_case = self.dummy_cond_unet _snake_case = PNDMScheduler(skip_prk_steps=_lowerCamelCase ) _snake_case = self.dummy_vae _snake_case = self.dummy_text_encoder _snake_case = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # make sure here that pndm scheduler skips prk _snake_case = StableDiffusionPipeline( unet=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , safety_checker=_lowerCamelCase , feature_extractor=self.dummy_extractor , ) _snake_case = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = '''A painting of a squirrel eating a burger''' _snake_case = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) _snake_case = sd_pipe([prompt] , generator=_lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' ) _snake_case = output.images _snake_case = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , return_dict=_lowerCamelCase , )[0] _snake_case = image[0, -3:, -3:, -1] _snake_case = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case = np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self : Optional[int] ): _snake_case = StableDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-lms-pipe''' , safety_checker=_lowerCamelCase ) assert isinstance(_lowerCamelCase , _lowerCamelCase ) assert isinstance(pipe.scheduler , _lowerCamelCase ) assert pipe.safety_checker is None _snake_case = pipe('''example prompt''' , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_lowerCamelCase ) _snake_case = StableDiffusionPipeline.from_pretrained(_lowerCamelCase ) # sanity check that the pipeline still works assert pipe.safety_checker is None _snake_case = pipe('''example prompt''' , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def lowercase ( self : List[str] ): _snake_case = self.dummy_cond_unet _snake_case = PNDMScheduler(skip_prk_steps=_lowerCamelCase ) _snake_case = self.dummy_vae _snake_case = self.dummy_text_encoder _snake_case = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # put models in fp16 _snake_case = unet.half() _snake_case = vae.half() _snake_case = bert.half() # make sure here that pndm scheduler skips prk _snake_case = StableDiffusionPipeline( unet=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , safety_checker=_lowerCamelCase , feature_extractor=self.dummy_extractor , ) _snake_case = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = '''A painting of a squirrel eating a burger''' _snake_case = sd_pipe([prompt] , num_inference_steps=2 , output_type='''np''' ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def lowercase ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : Union[str, Any] ): _snake_case = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' , safety_checker=_lowerCamelCase ) _snake_case = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) _snake_case = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = ( '''portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle''' ''' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with''' ''' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and''' ''' children from bahnhof zoo, detailed ''' ) _snake_case = 4003660346 _snake_case = 7 # without safety guidance (sld_guidance_scale = 0) _snake_case = torch.manual_seed(_lowerCamelCase ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=_lowerCamelCase , num_inference_steps=50 , output_type='''np''' , width=512 , height=512 , sld_guidance_scale=0 , ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] _snake_case = [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) _snake_case = torch.manual_seed(_lowerCamelCase ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=_lowerCamelCase , num_inference_steps=50 , output_type='''np''' , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] _snake_case = [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self : str ): _snake_case = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' , safety_checker=_lowerCamelCase ) _snake_case = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) _snake_case = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = '''padme amidala taking a bath artwork, safe for work, no nudity''' _snake_case = 2734971755 _snake_case = 7 _snake_case = torch.manual_seed(_lowerCamelCase ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=_lowerCamelCase , num_inference_steps=50 , output_type='''np''' , width=512 , height=512 , sld_guidance_scale=0 , ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] _snake_case = [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 _snake_case = torch.manual_seed(_lowerCamelCase ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=_lowerCamelCase , num_inference_steps=50 , output_type='''np''' , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] _snake_case = [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self : Union[str, Any] ): _snake_case = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' ) _snake_case = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) _snake_case = ( '''the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.''' ''' leyendecker''' ) _snake_case = 1044355234 _snake_case = 12 _snake_case = torch.manual_seed(_lowerCamelCase ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=_lowerCamelCase , num_inference_steps=50 , output_type='''np''' , width=512 , height=512 , sld_guidance_scale=0 , ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] _snake_case = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 _snake_case = torch.manual_seed(_lowerCamelCase ) _snake_case = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=_lowerCamelCase , num_inference_steps=50 , output_type='''np''' , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) _snake_case = output.images _snake_case = image[0, -3:, -3:, -1] _snake_case = np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
224
"""simple docstring""" import sys from collections import defaultdict class lowerCAmelCase__ : def __init__( self : List[str] ): _snake_case = [] def lowercase ( self : Optional[Any] , _lowerCamelCase : Union[str, Any] ): return self.node_position[vertex] def lowercase ( self : Optional[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[Any] ): _snake_case = pos def lowercase ( self : Any , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : str ): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: _snake_case = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: _snake_case = 2 * start + 1 else: _snake_case = 2 * start + 2 if heap[smallest_child] < heap[start]: _snake_case , _snake_case = heap[smallest_child], positions[smallest_child] _snake_case , _snake_case = ( heap[start], positions[start], ) _snake_case , _snake_case = temp, tempa _snake_case = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , _lowerCamelCase ) self.top_to_bottom(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def lowercase ( self : Dict , _lowerCamelCase : Tuple , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : Union[str, Any] ): _snake_case = position[index] while index != 0: _snake_case = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: _snake_case = heap[parent] _snake_case = position[parent] self.set_position(position[parent] , _lowerCamelCase ) else: _snake_case = val _snake_case = temp self.set_position(_lowerCamelCase , _lowerCamelCase ) break _snake_case = parent else: _snake_case = val _snake_case = temp self.set_position(_lowerCamelCase , 0 ) def lowercase ( self : Dict , _lowerCamelCase : Any , _lowerCamelCase : List[str] ): _snake_case = len(_lowerCamelCase ) // 2 - 1 for i in range(_lowerCamelCase , -1 , -1 ): self.top_to_bottom(_lowerCamelCase , _lowerCamelCase , len(_lowerCamelCase ) , _lowerCamelCase ) def lowercase ( self : str , _lowerCamelCase : int , _lowerCamelCase : List[str] ): _snake_case = positions[0] _snake_case = sys.maxsize self.top_to_bottom(_lowerCamelCase , 0 , len(_lowerCamelCase ) , _lowerCamelCase ) return temp def _UpperCAmelCase ( __lowerCamelCase : List[str] ) -> List[str]: _snake_case = Heap() _snake_case = [0] * len(__lowerCamelCase ) _snake_case = [-1] * len(__lowerCamelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph _snake_case = [] # Heap of Distance of vertices from their neighboring vertex _snake_case = [] for vertex in range(len(__lowerCamelCase ) ): distance_tv.append(sys.maxsize ) positions.append(__lowerCamelCase ) heap.node_position.append(__lowerCamelCase ) _snake_case = [] _snake_case = 1 _snake_case = sys.maxsize for neighbor, distance in adjacency_list[0]: _snake_case = 0 _snake_case = distance heap.heapify(__lowerCamelCase , __lowerCamelCase ) for _ in range(1 , len(__lowerCamelCase ) ): _snake_case = heap.delete_minimum(__lowerCamelCase , __lowerCamelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) _snake_case = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(__lowerCamelCase )] ): _snake_case = distance heap.bottom_to_top( __lowerCamelCase , heap.get_position(__lowerCamelCase ) , __lowerCamelCase , __lowerCamelCase ) _snake_case = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > UpperCAmelCase__ = int(input('Enter number of edges: ').strip()) UpperCAmelCase__ = defaultdict(list) for _ in range(edges_number): UpperCAmelCase__ = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
224
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCamelCase : List[str] = { 'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Dict = [ 'GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'GraphormerForGraphClassification', 'GraphormerModel', 'GraphormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys _UpperCamelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
134
"""simple docstring""" import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class a ( unittest.TestCase ): @property def UpperCamelCase_ ( self ): torch.manual_seed(0 ) lowercase = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def UpperCamelCase_ ( self ): torch.manual_seed(0 ) lowercase = VQModel( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def UpperCamelCase_ ( self ): torch.manual_seed(0 ) lowercase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(_lowerCamelCase ) def UpperCamelCase_ ( self ): lowercase = self.dummy_uncond_unet lowercase = DDIMScheduler() lowercase = self.dummy_vq_model lowercase = LDMPipeline(unet=_lowerCamelCase , vqvae=_lowerCamelCase , scheduler=_lowerCamelCase ) ldm.to(_lowerCamelCase ) ldm.set_progress_bar_config(disable=_lowerCamelCase ) lowercase = torch.manual_seed(0 ) lowercase = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type='numpy' ).images lowercase = torch.manual_seed(0 ) lowercase = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type='numpy' , return_dict=_lowerCamelCase )[0] lowercase = image[0, -3:, -3:, -1] lowercase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowercase = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) lowercase = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class a ( unittest.TestCase ): def UpperCamelCase_ ( self ): lowercase = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(_lowerCamelCase ) ldm.set_progress_bar_config(disable=_lowerCamelCase ) lowercase = torch.manual_seed(0 ) lowercase = ldm(generator=_lowerCamelCase , num_inference_steps=5 , output_type='numpy' ).images lowercase = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) lowercase = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) lowercase = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
134
1
'''simple docstring''' 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 snake_case_ (UpperCamelCase : List[Any] ): '''simple docstring''' _a = 384 if "tiny" in model_name: _a = [3, 3, 9, 3] _a = [96, 192, 384, 768] if "small" in model_name: _a = [3, 3, 27, 3] _a = [96, 192, 384, 768] if "base" in model_name: _a = [3, 3, 27, 3] _a = [128, 256, 512, 1024] _a = 512 if "large" in model_name: _a = [3, 3, 27, 3] _a = [192, 384, 768, 1536] _a = 768 if "xlarge" in model_name: _a = [3, 3, 27, 3] _a = [256, 512, 1024, 2048] _a = 1024 # set label information _a = 150 _a = '''huggingface/label-files''' _a = '''ade20k-id2label.json''' _a = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) ) _a = {int(UpperCamelCase ): v for k, v in idalabel.items()} _a = {v: k for k, v in idalabel.items()} _a = ConvNextConfig( depths=UpperCamelCase , hidden_sizes=UpperCamelCase , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) _a = UperNetConfig( backbone_config=UpperCamelCase , auxiliary_in_channels=UpperCamelCase , num_labels=UpperCamelCase , idalabel=UpperCamelCase , labelaid=UpperCamelCase , ) return config def snake_case_ (UpperCamelCase : str ): '''simple docstring''' _a = [] # 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 snake_case_ (UpperCamelCase : str , UpperCamelCase : Optional[Any] , UpperCamelCase : str ): '''simple docstring''' _a = dct.pop(UpperCamelCase ) _a = val def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[int] ): '''simple docstring''' _a = { '''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''', } _a = model_name_to_url[model_name] _a = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location='''cpu''' )['''state_dict'''] _a = get_upernet_config(UpperCamelCase ) _a = UperNetForSemanticSegmentation(UpperCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): _a = state_dict.pop(UpperCamelCase ) if "bn" in key: _a = key.replace('''bn''' , '''batch_norm''' ) _a = val # rename keys _a = create_rename_keys(UpperCamelCase ) for src, dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) model.load_state_dict(UpperCamelCase ) # verify on image _a = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' _a = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ).convert('''RGB''' ) _a = SegformerImageProcessor() _a = processor(UpperCamelCase , return_tensors='''pt''' ).pixel_values with torch.no_grad(): _a = model(UpperCamelCase ) if model_name == "upernet-convnext-tiny": _a = 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": _a = 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": _a = 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": _a = 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": _a = 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] , UpperCamelCase , 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(UpperCamelCase ) print(f'Saving processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(UpperCamelCase ) 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__": _snake_case : str = 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.' ) _snake_case : Dict = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
22
'''simple docstring''' import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) __SCREAMING_SNAKE_CASE : int = logging.getLogger(__name__) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' def _A ( self : str , A : Optional[int] , A : List[str] , A : List[str]=None , A : List[Any]=None ): _UpperCAmelCase : Union[str, Any] = self.layer[current_layer](A , A , head_mask[current_layer] ) _UpperCAmelCase : Tuple = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." , snake_case__ , ) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' def __init__( self : List[Any] , A : Tuple ): super().__init__(A ) _UpperCAmelCase : Optional[Any] = BertEncoderWithPabee(A ) self.init_weights() _UpperCAmelCase : Tuple = 0 _UpperCAmelCase : Optional[int] = 0 _UpperCAmelCase : Any = 0 _UpperCAmelCase : Optional[int] = 0 def _A ( self : Tuple , A : Tuple ): _UpperCAmelCase : Union[str, Any] = threshold def _A ( self : Optional[int] , A : Union[str, Any] ): _UpperCAmelCase : Any = patience def _A ( self : List[Any] ): _UpperCAmelCase : List[str] = 0 _UpperCAmelCase : List[str] = 0 def _A ( self : int ): _UpperCAmelCase : List[Any] = self.inference_layers_num / self.inference_instances_num _UpperCAmelCase : str = ( F"""*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =""" F""" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***""" ) print(A ) @add_start_docstrings_to_model_forward(A ) def _A ( self : Optional[int] , A : int=None , A : Union[str, Any]=None , A : int=None , A : List[Any]=None , A : Dict=None , A : Dict=None , A : Optional[int]=None , A : str=None , A : Union[str, Any]=None , A : Any=None , A : List[Any]=False , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: _UpperCAmelCase : Union[str, Any] = input_ids.size() elif inputs_embeds is not None: _UpperCAmelCase : Tuple = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds" ) _UpperCAmelCase : Optional[Any] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _UpperCAmelCase : Optional[int] = torch.ones(A , device=A ) if token_type_ids is None: _UpperCAmelCase : Optional[int] = torch.zeros(A , dtype=torch.long , device=A ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _UpperCAmelCase : torch.Tensor = self.get_extended_attention_mask(A , A , A ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Tuple = encoder_hidden_states.size() _UpperCAmelCase : Tuple = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: _UpperCAmelCase : Tuple = torch.ones(A , device=A ) _UpperCAmelCase : Optional[int] = self.invert_attention_mask(A ) else: _UpperCAmelCase : Optional[int] = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _UpperCAmelCase : List[str] = self.get_head_mask(A , self.config.num_hidden_layers ) _UpperCAmelCase : List[Any] = self.embeddings( input_ids=A , position_ids=A , token_type_ids=A , inputs_embeds=A ) _UpperCAmelCase : Optional[Any] = embedding_output if self.training: _UpperCAmelCase : Tuple = [] for i in range(self.config.num_hidden_layers ): _UpperCAmelCase : int = self.encoder.adaptive_forward( A , current_layer=A , attention_mask=A , head_mask=A ) _UpperCAmelCase : Dict = self.pooler(A ) _UpperCAmelCase : List[str] = output_layers[i](output_dropout(A ) ) res.append(A ) elif self.patience == 0: # Use all layers for inference _UpperCAmelCase : Tuple = self.encoder( A , attention_mask=A , head_mask=A , encoder_hidden_states=A , encoder_attention_mask=A , ) _UpperCAmelCase : List[str] = self.pooler(encoder_outputs[0] ) _UpperCAmelCase : str = [output_layers[self.config.num_hidden_layers - 1](A )] else: _UpperCAmelCase : Tuple = 0 _UpperCAmelCase : List[Any] = None _UpperCAmelCase : Tuple = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 _UpperCAmelCase : Union[str, Any] = self.encoder.adaptive_forward( A , current_layer=A , attention_mask=A , head_mask=A ) _UpperCAmelCase : int = self.pooler(A ) _UpperCAmelCase : Optional[Any] = output_layers[i](A ) if regression: _UpperCAmelCase : Dict = logits.detach() if patient_result is not None: _UpperCAmelCase : Tuple = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: _UpperCAmelCase : Dict = 0 else: _UpperCAmelCase : List[str] = logits.detach().argmax(dim=1 ) if patient_result is not None: _UpperCAmelCase : int = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(A ) ): patient_counter += 1 else: _UpperCAmelCase : int = 0 _UpperCAmelCase : Union[str, Any] = logits if patient_counter == self.patience: break _UpperCAmelCase : str = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " , snake_case__ , ) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' def __init__( self : List[str] , A : str ): super().__init__(A ) _UpperCAmelCase : Union[str, Any] = config.num_labels _UpperCAmelCase : int = BertModelWithPabee(A ) _UpperCAmelCase : List[str] = nn.Dropout(config.hidden_dropout_prob ) _UpperCAmelCase : Any = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(A ) def _A ( self : Union[str, Any] , A : Any=None , A : Optional[int]=None , A : str=None , A : str=None , A : Optional[Any]=None , A : int=None , A : str=None , ): _UpperCAmelCase : Any = self.bert( input_ids=A , attention_mask=A , token_type_ids=A , position_ids=A , head_mask=A , inputs_embeds=A , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) _UpperCAmelCase : List[Any] = (logits[-1],) if labels is not None: _UpperCAmelCase : Optional[int] = None _UpperCAmelCase : Any = 0 for ix, logits_item in enumerate(A ): if self.num_labels == 1: # We are doing regression _UpperCAmelCase : List[Any] = MSELoss() _UpperCAmelCase : Optional[Any] = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: _UpperCAmelCase : int = CrossEntropyLoss() _UpperCAmelCase : Any = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: _UpperCAmelCase : Dict = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 _UpperCAmelCase : List[Any] = (total_loss / total_weights,) + outputs return outputs
244
0
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Dict: """simple docstring""" for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})""" def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_=True ) -> Union[str, Any]: """simple docstring""" model.train() A__ = model(lowercase_ ) A__ = F.mse_loss(lowercase_ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=False ) -> Optional[int]: """simple docstring""" set_seed(42 ) A__ = RegressionModel() A__ = deepcopy(lowercase_ ) A__ = RegressionDataset(length=80 ) A__ = DataLoader(lowercase_ , batch_size=16 ) model.to(accelerator.device ) if sched: A__ = AdamW(params=model.parameters() , lr=1E-3 ) A__ = AdamW(params=ddp_model.parameters() , lr=1E-3 ) A__ = LambdaLR(lowercase_ , lr_lambda=lambda lowercase_ : epoch**0.65 ) A__ = LambdaLR(lowercase_ , lr_lambda=lambda lowercase_ : epoch**0.65 ) # Make a copy of `model` if sched: A__ , A__ , A__ , A__ = accelerator.prepare(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) else: A__ , A__ = accelerator.prepare(lowercase_ , lowercase_ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[Any]: """simple docstring""" A__ , A__ , A__ = get_training_setup(lowercase_ ) # Use a single batch A__ , A__ = next(iter(lowercase_ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model A__ , A__ = accelerator.gather((ddp_input, ddp_target) ) A__ , A__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowercase_ ): step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) else: # Sync grads step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) A__ = ddp_input[torch.randperm(len(lowercase_ ) )] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" A__ , A__ , A__ = get_training_setup(lowercase_ ) # Use a single batch A__ , A__ = next(iter(lowercase_ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model A__ , A__ = accelerator.gather((ddp_input, ddp_target) ) A__ , A__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowercase_ ): step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) else: # Sync grads step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f"""Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) A__ = ddp_input[torch.randperm(len(lowercase_ ) )] def SCREAMING_SNAKE_CASE ( lowercase_=False , lowercase_=False ) -> Tuple: """simple docstring""" A__ = Accelerator( split_batches=lowercase_ , dispatch_batches=lowercase_ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly A__ , A__ , A__ = get_training_setup(lowercase_ ) for iteration, batch in enumerate(lowercase_ ): A__ , A__ = batch.values() # Gather the distributed inputs and targs for the base model A__ , A__ = accelerator.gather((ddp_input, ddp_target) ) A__ , A__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(lowercase_ ): step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(lowercase_ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) A__ = ddp_input[torch.randperm(len(lowercase_ ) )] GradientState._reset_state() def SCREAMING_SNAKE_CASE ( lowercase_=False , lowercase_=False ) -> List[Any]: """simple docstring""" A__ = Accelerator( split_batches=lowercase_ , dispatch_batches=lowercase_ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly A__ , A__ , A__ , A__ , A__ , A__ , A__ = get_training_setup(lowercase_ , lowercase_ ) for iteration, batch in enumerate(lowercase_ ): A__ , A__ = batch.values() # Gather the distributed inputs and targs for the base model A__ , A__ = accelerator.gather((ddp_input, ddp_target) ) A__ , A__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(lowercase_ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(lowercase_ ): step_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f"""Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n""" A__ = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(lowercase_ )) if accelerator.num_processes > 1: check_model_parameters(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" A__ = Accelerator() A__ = RegressionDataset(length=80 ) A__ = DataLoader(lowercase_ , batch_size=16 ) A__ = RegressionDataset(length=96 ) A__ = DataLoader(lowercase_ , batch_size=16 ) A__ , A__ = accelerator.prepare(lowercase_ , lowercase_ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(lowercase_ ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowercase_ ) if iteration < len(lowercase_ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(lowercase_ ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowercase_ ) if batch_num < len(lowercase_ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" A__ = Accelerator() A__ = accelerator.state if state.local_process_index == 0: print('''**Test `accumulate` gradient accumulation with dataloader break**''' ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print('''**Test NOOP `no_sync` context manager**''' ) test_noop_sync(lowercase_ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print('''**Test Distributed `no_sync` context manager**''' ) test_distributed_sync(lowercase_ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation, ''' , f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" , ) test_gradient_accumulation(lowercase_ , lowercase_ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version('''<''' , '''2.0''' ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''' , '''`split_batches=False`, `dispatch_batches=False`**''' , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''' , f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" , ) test_gradient_accumulation_with_opt_and_scheduler(lowercase_ , lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Tuple: """simple docstring""" main() if __name__ == "__main__": main()
713
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowerCamelCase : List[str] = (720, 1280) # Height, Width _lowerCamelCase : Optional[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowerCamelCase : List[Any] = 1 / 100 _lowerCamelCase : List[str] = """""" _lowerCamelCase : List[str] = """""" _lowerCamelCase : List[str] = """""" _lowerCamelCase : Union[str, Any] = 250 def SCREAMING_SNAKE_CASE ( ) -> None: """simple docstring""" A__ , A__ = get_dataset(lowercase_ , lowercase_ ) for index in range(lowercase_ ): A__ = random.sample(range(len(lowercase_ ) ) , 4 ) A__ , A__ , A__ = update_image_and_anno( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , filter_scale=lowercase_ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' A__ = random_chars(32 ) A__ = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] A__ = f"""{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}""" cva.imwrite(f"""{file_root}.jpg""" , lowercase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"""Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}""" ) A__ = [] for anno in new_annos: A__ = anno[3] - anno[1] A__ = anno[4] - anno[2] A__ = anno[1] + width / 2 A__ = anno[2] + height / 2 A__ = f"""{anno[0]} {x_center} {y_center} {width} {height}""" annos_list.append(lowercase_ ) with open(f"""{file_root}.txt""" , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> tuple[list, list]: """simple docstring""" A__ = [] A__ = [] for label_file in glob.glob(os.path.join(lowercase_ , '''*.txt''' ) ): A__ = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(lowercase_ ) as in_file: A__ = in_file.readlines() A__ = os.path.join(lowercase_ , f"""{label_name}.jpg""" ) A__ = [] for obj_list in obj_lists: A__ = obj_list.rstrip('''\n''' ).split(''' ''' ) A__ = float(obj[1] ) - float(obj[3] ) / 2 A__ = float(obj[2] ) - float(obj[4] ) / 2 A__ = float(obj[1] ) + float(obj[3] ) / 2 A__ = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(lowercase_ ) labels.append(lowercase_ ) return img_paths, labels def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" A__ = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) A__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) A__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) A__ = int(scale_x * output_size[1] ) A__ = int(scale_y * output_size[0] ) A__ = [] A__ = [] for i, index in enumerate(lowercase_ ): A__ = all_img_list[index] path_list.append(lowercase_ ) A__ = all_annos[index] A__ = cva.imread(lowercase_ ) if i == 0: # top-left A__ = cva.resize(lowercase_ , (divid_point_x, divid_point_y) ) A__ = img for bbox in img_annos: A__ = bbox[1] * scale_x A__ = bbox[2] * scale_y A__ = bbox[3] * scale_x A__ = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right A__ = cva.resize(lowercase_ , (output_size[1] - divid_point_x, divid_point_y) ) A__ = img for bbox in img_annos: A__ = scale_x + bbox[1] * (1 - scale_x) A__ = bbox[2] * scale_y A__ = scale_x + bbox[3] * (1 - scale_x) A__ = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left A__ = cva.resize(lowercase_ , (divid_point_x, output_size[0] - divid_point_y) ) A__ = img for bbox in img_annos: A__ = bbox[1] * scale_x A__ = scale_y + bbox[2] * (1 - scale_y) A__ = bbox[3] * scale_x A__ = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right A__ = cva.resize( lowercase_ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) A__ = img for bbox in img_annos: A__ = scale_x + bbox[1] * (1 - scale_x) A__ = scale_y + bbox[2] * (1 - scale_y) A__ = scale_x + bbox[3] * (1 - scale_x) A__ = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: A__ = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" A__ = ascii_lowercase + digits return "".join(random.choice(lowercase_ ) for _ in range(lowercase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
177
0
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin a : int = random.Random() def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : Optional[int]=1.0 , _UpperCAmelCase : List[Any]=None , _UpperCAmelCase : Union[str, Any]=None ) -> List[Any]: if rng is None: __snake_case = global_rng __snake_case = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self : List[str] , a_ : List[str] , a_ : Union[str, Any]=7 , a_ : List[str]=400 , a_ : Dict=2_000 , a_ : Optional[Any]=1 , a_ : List[str]=0.0 , a_ : List[str]=16_000 , a_ : str=True , a_ : Optional[int]=True , ): """simple docstring""" __snake_case = parent __snake_case = batch_size __snake_case = min_seq_length __snake_case = max_seq_length __snake_case = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __snake_case = feature_size __snake_case = padding_value __snake_case = sampling_rate __snake_case = return_attention_mask __snake_case = do_normalize def A ( self : int ): """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def A ( self : Tuple , a_ : Any=False , a_ : Union[str, Any]=False ): """simple docstring""" def _flatten(a_ : Optional[Any] ): return list(itertools.chain(*a_ ) ) if equal_length: __snake_case = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __snake_case = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __snake_case = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor def A ( self : List[Any] ): """simple docstring""" __snake_case = WavaVecaFeatureExtractionTester(self ) def A ( self : Tuple , a_ : Optional[int] ): """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def A ( self : Optional[int] ): """simple docstring""" __snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __snake_case = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input __snake_case = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values __snake_case = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched __snake_case = feat_extract(a_ , return_tensors="np" ).input_values __snake_case = feat_extract(a_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __snake_case = [floats_list((1, x) )[0] for x in (800, 800, 800)] __snake_case = np.asarray(a_ ) __snake_case = feat_extract(a_ , return_tensors="np" ).input_values __snake_case = feat_extract(a_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def A ( self : Optional[Any] ): """simple docstring""" __snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __snake_case = ["longest", "max_length", "do_not_pad"] __snake_case = [None, 1_600, None] for max_length, padding in zip(a_ , a_ ): __snake_case = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors="np" ) __snake_case = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self.assertTrue(input_values[0][1_000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def A ( self : Optional[Any] ): """simple docstring""" __snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __snake_case = range(800 , 1_400 , 200 ) __snake_case = [floats_list((1, x) )[0] for x in lengths] __snake_case = ["longest", "max_length", "do_not_pad"] __snake_case = [None, 1_600, None] for max_length, padding in zip(a_ , a_ ): __snake_case = feat_extract(a_ , max_length=a_ , padding=a_ ) __snake_case = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def A ( self : str ): """simple docstring""" __snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __snake_case = feat_extract( a_ , truncation=a_ , max_length=1_000 , padding="max_length" , return_tensors="np" ) __snake_case = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def A ( self : Optional[int] ): """simple docstring""" __snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __snake_case = feat_extract( a_ , truncation=a_ , max_length=1_000 , padding="longest" , return_tensors="np" ) __snake_case = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_000) ) __snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __snake_case = feat_extract( a_ , truncation=a_ , max_length=2_000 , padding="longest" , return_tensors="np" ) __snake_case = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_200) ) @require_torch def A ( self : Tuple ): """simple docstring""" import torch __snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __snake_case = np.random.rand(100 ).astype(np.floataa ) __snake_case = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __snake_case = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __snake_case = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def A ( self : str ): """simple docstring""" for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: __snake_case = WavaVecaConfig.from_pretrained(a_ ) __snake_case = WavaVecaFeatureExtractor.from_pretrained(a_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == "layer" )
69
'''simple docstring''' def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int: assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 __snake_case , __snake_case = 1, 1 for _ in range(number_of_steps - 1 ): __snake_case , __snake_case = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
69
1
'''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 _lowerCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : str=13 , UpperCamelCase_ : Dict=32 , UpperCamelCase_ : Union[str, Any]=3 , UpperCamelCase_ : str=4 , UpperCamelCase_ : Any=[10, 20, 30, 40] , UpperCamelCase_ : Optional[int]=[2, 2, 3, 2] , UpperCamelCase_ : Dict=True , UpperCamelCase_ : List[Any]=True , UpperCamelCase_ : List[str]=37 , UpperCamelCase_ : str="gelu" , UpperCamelCase_ : Union[str, Any]=10 , UpperCamelCase_ : str=0.02 , UpperCamelCase_ : Optional[int]=["stage2", "stage3", "stage4"] , UpperCamelCase_ : List[Any]=[2, 3, 4] , UpperCamelCase_ : Dict=None , ) -> Dict: '''simple docstring''' _lowercase : Union[str, Any] = parent _lowercase : int = batch_size _lowercase : Optional[int] = image_size _lowercase : Optional[int] = num_channels _lowercase : List[str] = num_stages _lowercase : Union[str, Any] = hidden_sizes _lowercase : Tuple = depths _lowercase : int = is_training _lowercase : List[Any] = use_labels _lowercase : str = intermediate_size _lowercase : Optional[Any] = hidden_act _lowercase : Optional[int] = num_labels _lowercase : List[Any] = initializer_range _lowercase : int = out_features _lowercase : List[str] = out_indices _lowercase : Optional[Any] = scope def __lowercase ( self : Optional[int] ) -> int: '''simple docstring''' _lowercase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowercase : Any = None if self.use_labels: _lowercase : Dict = ids_tensor([self.batch_size] , self.num_labels ) _lowercase : Any = self.get_config() return config, pixel_values, labels def __lowercase ( self : Optional[Any] ) -> List[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=UpperCamelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def __lowercase ( self : Optional[int] , UpperCamelCase_ : str , UpperCamelCase_ : Any , UpperCamelCase_ : int ) -> Union[str, Any]: '''simple docstring''' _lowercase : Optional[Any] = ConvNextModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() _lowercase : List[Any] = model(UpperCamelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase ( self : Union[str, Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any ) -> List[str]: '''simple docstring''' _lowercase : Dict = ConvNextForImageClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() _lowercase : Optional[int] = model(UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase ( self : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[Any] ) -> Optional[int]: '''simple docstring''' _lowercase : List[Any] = ConvNextBackbone(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() _lowercase : Tuple = model(UpperCamelCase_ ) # 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 _lowercase : Dict = None _lowercase : List[Any] = ConvNextBackbone(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() _lowercase : Tuple = model(UpperCamelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def __lowercase ( self : int ) -> List[str]: '''simple docstring''' _lowercase : List[str] = self.prepare_config_and_inputs() _lowercase , _lowercase , _lowercase : Tuple = config_and_inputs _lowercase : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase ( __A , __A , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) snake_case_ = ( {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification} if is_torch_available() else {} ) snake_case_ = True snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def __lowercase ( self : Any ) -> int: '''simple docstring''' _lowercase : Tuple = ConvNextModelTester(self ) _lowercase : str = ConfigTester(self , config_class=UpperCamelCase_ , has_text_modality=UpperCamelCase_ , hidden_size=37 ) def __lowercase ( self : Tuple ) -> Optional[int]: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' return @unittest.skip(reason='''ConvNext does not use inputs_embeds''' ) def __lowercase ( self : Tuple ) -> List[Any]: '''simple docstring''' pass @unittest.skip(reason='''ConvNext does not support input and output embeddings''' ) def __lowercase ( self : Any ) -> Optional[int]: '''simple docstring''' pass @unittest.skip(reason='''ConvNext does not use feedforward chunking''' ) def __lowercase ( self : str ) -> List[Any]: '''simple docstring''' pass def __lowercase ( self : Optional[int] ) -> List[Any]: '''simple docstring''' _lowercase , _lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : Any = model_class(UpperCamelCase_ ) _lowercase : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowercase : List[Any] = [*signature.parameters.keys()] _lowercase : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase_ ) def __lowercase ( self : int ) -> Dict: '''simple docstring''' _lowercase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def __lowercase ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' _lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*UpperCamelCase_ ) def __lowercase ( self : Dict ) -> List[str]: '''simple docstring''' def check_hidden_states_output(UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Union[str, Any] ): _lowercase : Optional[Any] = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() with torch.no_grad(): _lowercase : Any = model(**self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) ) _lowercase : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowercase : List[Any] = self.model_tester.num_stages self.assertEqual(len(UpperCamelCase_ ) , 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] , ) _lowercase , _lowercase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : str = True check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowercase : Tuple = True check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def __lowercase ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_ ) @slow def __lowercase ( self : List[str] ) -> List[str]: '''simple docstring''' for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : int = ConvNextModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) def _SCREAMING_SNAKE_CASE( ) ->Any: '''simple docstring''' _lowercase : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __lowercase ( self : int ) -> Optional[int]: '''simple docstring''' return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224''' ) if is_vision_available() else None @slow def __lowercase ( self : int ) -> List[Any]: '''simple docstring''' _lowercase : List[Any] = ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''' ).to(UpperCamelCase_ ) _lowercase : Union[str, Any] = self.default_image_processor _lowercase : str = prepare_img() _lowercase : Tuple = image_processor(images=UpperCamelCase_ , return_tensors='''pt''' ).to(UpperCamelCase_ ) # forward pass with torch.no_grad(): _lowercase : List[Any] = model(**UpperCamelCase_ ) # verify the logits _lowercase : int = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase_ ) _lowercase : int = torch.tensor([-0.0_260, -0.4_739, 0.1_911] ).to(UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase_ , atol=1e-4 ) ) @require_torch class _lowerCAmelCase ( unittest.TestCase , __A ): '''simple docstring''' snake_case_ = (ConvNextBackbone,) if is_torch_available() else () snake_case_ = ConvNextConfig snake_case_ = False def __lowercase ( self : List[str] ) -> Any: '''simple docstring''' _lowercase : Any = ConvNextModelTester(self )
411
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase__ = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } lowerCamelCase__ = { 'yjernite/retribert-base-uncased': 5_12, } lowerCamelCase__ = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class _lowerCAmelCase ( __A ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = RetriBertTokenizer snake_case_ = ['input_ids', 'attention_mask'] def __init__( self : str , UpperCamelCase_ : List[Any]=None , UpperCamelCase_ : str=None , UpperCamelCase_ : Tuple=True , UpperCamelCase_ : str="[UNK]" , UpperCamelCase_ : Optional[int]="[SEP]" , UpperCamelCase_ : Union[str, Any]="[PAD]" , UpperCamelCase_ : List[Any]="[CLS]" , UpperCamelCase_ : int="[MASK]" , UpperCamelCase_ : Optional[int]=True , UpperCamelCase_ : Tuple=None , **UpperCamelCase_ : List[Any] , ) -> Union[str, Any]: '''simple docstring''' super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) _lowercase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCamelCase_ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCamelCase_ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCamelCase_ ) != tokenize_chinese_chars ): _lowercase : Any = getattr(UpperCamelCase_ , normalizer_state.pop('''type''' ) ) _lowercase : Any = do_lower_case _lowercase : List[Any] = strip_accents _lowercase : Union[str, Any] = tokenize_chinese_chars _lowercase : Optional[int] = normalizer_class(**UpperCamelCase_ ) _lowercase : str = do_lower_case def __lowercase ( self : Optional[int] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : str=None ) -> Any: '''simple docstring''' _lowercase : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowercase ( self : int , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _lowercase : List[str] = [self.sep_token_id] _lowercase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowercase ( self : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' _lowercase : str = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ )
411
1
'''simple docstring''' import warnings from ..trainer import Trainer from ..utils import logging lowercase = logging.get_logger(__name__) class __lowerCamelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , a__=None , **a__ ): warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , a__ , ) super().__init__(args=a__ , **a__ )
211
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case__ : Dict = TextToVideoSDPipeline snake_case__ : str = TEXT_TO_IMAGE_PARAMS snake_case__ : Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. snake_case__ : Tuple = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def a_ ( self ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) __SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=a__ , set_alpha_to_one=a__ , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Tuple = 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 : Union[str, Any] = CLIPTextModel(a__ ) __SCREAMING_SNAKE_CASE : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __SCREAMING_SNAKE_CASE : int = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a_ ( self , a__ , a__=0 ): if str(a__ ).startswith("mps" ): __SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(a__ ) else: __SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=a__ ).manual_seed(a__ ) __SCREAMING_SNAKE_CASE : Optional[int] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a_ ( self ): __SCREAMING_SNAKE_CASE : Optional[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : str = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Optional[int] = TextToVideoSDPipeline(**a__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) __SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs(a__ ) __SCREAMING_SNAKE_CASE : Any = "np" __SCREAMING_SNAKE_CASE : str = sd_pipe(**a__ ).frames __SCREAMING_SNAKE_CASE : Optional[int] = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) __SCREAMING_SNAKE_CASE : str = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=a__ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a__ , expected_max_diff=1e-2 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a_ ( self ): pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a_ ( self ): pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a_ ( self ): pass def a_ ( self ): return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def a_ ( self ): __SCREAMING_SNAKE_CASE : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy" ) __SCREAMING_SNAKE_CASE : Optional[Any] = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) __SCREAMING_SNAKE_CASE : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) __SCREAMING_SNAKE_CASE : List[Any] = pipe.to("cuda" ) __SCREAMING_SNAKE_CASE : Dict = "Spiderman is surfing" __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device="cpu" ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(a__ , generator=a__ , num_inference_steps=25 , output_type="pt" ).frames __SCREAMING_SNAKE_CASE : Optional[Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def a_ ( self ): __SCREAMING_SNAKE_CASE : int = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy" ) __SCREAMING_SNAKE_CASE : List[Any] = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) __SCREAMING_SNAKE_CASE : Optional[int] = pipe.to("cuda" ) __SCREAMING_SNAKE_CASE : List[str] = "Spiderman is surfing" __SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device="cpu" ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Any = pipe(a__ , generator=a__ , num_inference_steps=2 , output_type="pt" ).frames __SCREAMING_SNAKE_CASE : List[Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
211
1
'''simple docstring''' from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase : List[Any] = logging.get_logger(__name__) class lowerCamelCase (a__ ): _lowercase : int = ["""pixel_values"""] def __init__( self , lowercase__ = True , lowercase__ = None , lowercase__ = PILImageResampling.BICUBIC , lowercase__ = True , lowercase__ = None , lowercase__ = True , lowercase__ = 1 / 255 , lowercase__ = True , lowercase__ = IMAGENET_DEFAULT_MEAN , lowercase__ = IMAGENET_DEFAULT_STD , **lowercase__ , ) -> None: """simple docstring""" super().__init__(**lowercase__ ) _snake_case : Any = size if size is not None else {'''shortest_edge''': 224} _snake_case : Union[str, Any] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) _snake_case : Optional[int] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} _snake_case : str = get_size_dict(lowercase__ , param_name='''crop_size''' ) _snake_case : Optional[Any] = do_resize _snake_case : Tuple = size _snake_case : Dict = resample _snake_case : Optional[int] = do_center_crop _snake_case : List[str] = crop_size _snake_case : int = do_rescale _snake_case : Dict = rescale_factor _snake_case : List[str] = do_normalize _snake_case : Tuple = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN _snake_case : List[Any] = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase_ ( self , lowercase__ , lowercase__ , lowercase__ = PILImageResampling.BICUBIC , lowercase__ = None , **lowercase__ , ) -> np.ndarray: """simple docstring""" _snake_case : Optional[Any] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: _snake_case : Union[str, Any] = int((256 / 224) * size['''shortest_edge'''] ) _snake_case : Tuple = get_resize_output_image_size(lowercase__ , size=lowercase__ , default_to_square=lowercase__ ) _snake_case : str = {'''height''': output_size[0], '''width''': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F'''Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}''' ) return resize( lowercase__ , size=(size_dict['''height'''], size_dict['''width''']) , resample=lowercase__ , data_format=lowercase__ , **lowercase__ ) def UpperCAmelCase_ ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ) -> np.ndarray: """simple docstring""" _snake_case : Union[str, Any] = get_size_dict(lowercase__ ) if "height" not in size or "width" not in size: raise ValueError(F'''Size dict must have keys \'height\' and \'width\'. Got {size.keys()}''' ) return center_crop(lowercase__ , size=(size['''height'''], size['''width''']) , data_format=lowercase__ , **lowercase__ ) def UpperCAmelCase_ ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ) -> np.ndarray: """simple docstring""" return rescale(lowercase__ , scale=lowercase__ , data_format=lowercase__ , **lowercase__ ) def UpperCAmelCase_ ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ) -> np.ndarray: """simple docstring""" return normalize(lowercase__ , mean=lowercase__ , std=lowercase__ , data_format=lowercase__ , **lowercase__ ) def UpperCAmelCase_ ( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = ChannelDimension.FIRST , **lowercase__ , ) -> BatchFeature: """simple docstring""" _snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize _snake_case : Dict = resample if resample is not None else self.resample _snake_case : Any = do_center_crop if do_center_crop is not None else self.do_center_crop _snake_case : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale _snake_case : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor _snake_case : List[str] = do_normalize if do_normalize is not None else self.do_normalize _snake_case : List[Any] = image_mean if image_mean is not None else self.image_mean _snake_case : Union[str, Any] = image_std if image_std is not None else self.image_std _snake_case : Tuple = size if size is not None else self.size _snake_case : Optional[Any] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) _snake_case : Union[str, Any] = crop_size if crop_size is not None else self.crop_size _snake_case : str = get_size_dict(lowercase__ , param_name='''crop_size''' ) _snake_case : str = make_list_of_images(lowercase__ ) if not valid_images(lowercase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. _snake_case : List[Any] = [to_numpy_array(lowercase__ ) for image in images] if do_resize: _snake_case : Optional[int] = [self.resize(lowercase__ , lowercase__ , lowercase__ ) for image in images] if do_center_crop: _snake_case : Tuple = [self.center_crop(lowercase__ , lowercase__ ) for image in images] if do_rescale: _snake_case : Optional[Any] = [self.rescale(lowercase__ , lowercase__ ) for image in images] if do_normalize: _snake_case : str = [self.normalize(lowercase__ , lowercase__ , lowercase__ ) for image in images] _snake_case : int = [to_channel_dimension_format(lowercase__ , lowercase__ ) for image in images] _snake_case : Dict = {'''pixel_values''': images} return BatchFeature(data=lowercase__ , tensor_type=lowercase__ )
714
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : int = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST', 'PegasusXForConditionalGeneration', 'PegasusXModel', 'PegasusXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys UpperCAmelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
47
0
from math import factorial UpperCAmelCase__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def A ( snake_case__ : int ) -> int: '''simple docstring''' if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(snake_case__ ) ) def A ( snake_case__ : int = 60 , snake_case__ : int = 100_0000 ) -> int: '''simple docstring''' if not isinstance(snake_case__ , snake_case__ ) or not isinstance(snake_case__ , snake_case__ ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case = 0 # the cached sizes of the previous chains __snake_case = {} for start_chain_element in range(1 , snake_case__ ): # The temporary set will contain the elements of the chain __snake_case = set() __snake_case = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(snake_case__ ) chain_set_length += 1 __snake_case = digit_factorial_sum(snake_case__ ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
313
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCAmelCase__ : Union[str, Any] = logging.getLogger(__name__) class __lowercase ( lowerCamelCase__ ): def __init__( self , lowercase_ , lowercase_ , lowercase_ , lowercase_=None) -> List[Any]: super().__init__( lowercase_ , question_encoder_tokenizer=lowercase_ , generator_tokenizer=lowercase_ , index=lowercase_ , init_retrieval=lowercase_ , ) __snake_case = None def _a ( self , lowercase_) -> Union[str, Any]: logger.info('initializing retrieval') # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info('dist initialized') # needs to be set manually __snake_case = self._infer_socket_ifname() # avoid clash with the NCCL port __snake_case = str(distributed_port + 1) __snake_case = dist.new_group(ranks=lowercase_ , backend='gloo') # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info('dist not initialized / main') self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group) def _a ( self) -> int: return dist.get_rank(group=self.process_group) == 0 def _a ( self , lowercase_ , lowercase_ , lowercase_=torch.floataa) -> Dict: __snake_case = torch.empty(lowercase_ , dtype=lowercase_) dist.scatter(lowercase_ , src=0 , scatter_list=lowercase_ , group=self.process_group) return target_tensor def _a ( self) -> str: __snake_case = psutil.net_if_addrs() # a hacky way to deal with varying network interface names __snake_case = next((addr for addr in addrs if addr.startswith('e')) , lowercase_) return ifname def _a ( self , lowercase_ , lowercase_) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): __snake_case , __snake_case = self._main_retrieve(lowercase_ , lowercase_) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase_) # distributed training __snake_case = dist.get_world_size(group=self.process_group) # gather logic __snake_case = None if self._is_main(): __snake_case = [torch.empty(question_hidden_states.shape , dtype=torch.floataa) for _ in range(lowercase_)] dist.gather(torch.tensor(lowercase_) , dst=0 , gather_list=lowercase_ , group=self.process_group) # scatter logic __snake_case = question_hidden_states.shape[0] __snake_case = [] __snake_case = [] if self._is_main(): assert len(lowercase_) == world_size __snake_case , __snake_case = self._main_retrieve(torch.cat(lowercase_).numpy() , lowercase_) __snake_case , __snake_case = torch.tensor(lowercase_), torch.tensor(lowercase_) __snake_case = self._chunk_tensor(lowercase_ , lowercase_) __snake_case = self._chunk_tensor(lowercase_ , lowercase_) __snake_case = self._scattered(lowercase_ , [n_queries, n_docs] , target_type=torch.intaa) __snake_case = self._scattered(lowercase_ , [n_queries, n_docs, question_hidden_states.shape[1]]) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(lowercase_)
313
1
import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.bert.modeling_flax_bert import ( FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, ) class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def __init__( self :Optional[int], snake_case :List[str], snake_case :Tuple=13, snake_case :List[Any]=7, snake_case :List[str]=True, snake_case :List[str]=True, snake_case :int=True, snake_case :List[Any]=True, snake_case :str=99, snake_case :Optional[int]=32, snake_case :str=5, snake_case :Optional[Any]=4, snake_case :int=37, snake_case :Tuple="gelu", snake_case :Optional[int]=0.1, snake_case :Tuple=0.1, snake_case :Optional[int]=512, snake_case :Optional[Any]=16, snake_case :Tuple=2, snake_case :List[str]=0.0_2, snake_case :Any=4, ): """simple docstring""" _lowercase =parent _lowercase =batch_size _lowercase =seq_length _lowercase =is_training _lowercase =use_attention_mask _lowercase =use_token_type_ids _lowercase =use_labels _lowercase =vocab_size _lowercase =hidden_size _lowercase =num_hidden_layers _lowercase =num_attention_heads _lowercase =intermediate_size _lowercase =hidden_act _lowercase =hidden_dropout_prob _lowercase =attention_probs_dropout_prob _lowercase =max_position_embeddings _lowercase =type_vocab_size _lowercase =type_sequence_label_size _lowercase =initializer_range _lowercase =num_choices def UpperCamelCase__ ( self :str): """simple docstring""" _lowercase =ids_tensor([self.batch_size, self.seq_length], self.vocab_size) _lowercase =None if self.use_attention_mask: _lowercase =random_attention_mask([self.batch_size, self.seq_length]) _lowercase =None if self.use_token_type_ids: _lowercase =ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) _lowercase =BertConfig( 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=snake_case, initializer_range=self.initializer_range, ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase__ ( self :Optional[int]): """simple docstring""" _lowercase =self.prepare_config_and_inputs() _lowercase =config_and_inputs _lowercase ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def UpperCamelCase__ ( self :str): """simple docstring""" _lowercase =self.prepare_config_and_inputs() _lowercase =config_and_inputs _lowercase =True _lowercase =floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) _lowercase =ids_tensor([self.batch_size, self.seq_length], vocab_size=2) return ( config, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, ) @require_flax class SCREAMING_SNAKE_CASE_ ( UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" __lowerCAmelCase : Optional[Any] =True __lowerCAmelCase : Any =( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase__ ( self :List[Any]): """simple docstring""" _lowercase =FlaxBertModelTester(self) @slow def UpperCamelCase__ ( self :Union[str, Any]): """simple docstring""" _lowercase =FlaxBertModel.from_pretrained('bert-base-cased') _lowercase =model(np.ones((1, 1))) self.assertIsNotNone(snake_case)
714
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _SCREAMING_SNAKE_CASE = { "configuration_encodec": [ "ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP", "EncodecConfig", ], "feature_extraction_encodec": ["EncodecFeatureExtractor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ "ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST", "EncodecModel", "EncodecPreTrainedModel", ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
557
0
"""simple docstring""" from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase_ : def __init__( self , UpperCamelCase_ = None ) -> None: if components is None: __lowercase : Optional[int] = [] __lowercase : List[Any] = list(UpperCamelCase_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(UpperCamelCase_ , self.__components ) ) + ")" def __add__( self , UpperCamelCase_ ) -> Vector: __lowercase : Any = len(self ) if size == len(UpperCamelCase_ ): __lowercase : List[str] = [self.__components[i] + other.component(UpperCamelCase_ ) for i in range(UpperCamelCase_ )] return Vector(UpperCamelCase_ ) else: raise Exception('''must have the same size''' ) def __sub__( self , UpperCamelCase_ ) -> Vector: __lowercase : Dict = len(self ) if size == len(UpperCamelCase_ ): __lowercase : str = [self.__components[i] - other.component(UpperCamelCase_ ) for i in range(UpperCamelCase_ )] return Vector(UpperCamelCase_ ) else: # error case raise Exception('''must have the same size''' ) @overload def __mul__( self , UpperCamelCase_ ) -> Vector: ... @overload def __mul__( self , UpperCamelCase_ ) -> float: ... def __mul__( self , UpperCamelCase_ ) -> float | Vector: if isinstance(UpperCamelCase_ , (float, int) ): __lowercase : List[str] = [c * other for c in self.__components] return Vector(UpperCamelCase_ ) elif isinstance(UpperCamelCase_ , UpperCamelCase_ ) and len(self ) == len(UpperCamelCase_ ): __lowercase : Optional[Any] = len(self ) __lowercase : str = [self.__components[i] * other.component(UpperCamelCase_ ) for i in range(UpperCamelCase_ )] return sum(UpperCamelCase_ ) else: # error case raise Exception('''invalid operand!''' ) def _lowerCamelCase ( self ) -> Vector: return Vector(self.__components ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> float: if isinstance(UpperCamelCase_ , UpperCamelCase_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('''index out of range''' ) def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __lowercase : List[str] = value def _lowerCamelCase ( self ) -> float: if len(self.__components ) == 0: raise Exception('''Vector is empty''' ) __lowercase : List[Any] = [c**2 for c in self.__components] return math.sqrt(sum(UpperCamelCase_ ) ) def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = False ) -> float: __lowercase : List[str] = self * other __lowercase : int = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def __UpperCAmelCase ( __UpperCamelCase ): assert isinstance(__UpperCamelCase , __UpperCamelCase ) return Vector([0] * dimension ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): assert isinstance(__UpperCamelCase , __UpperCamelCase ) and (isinstance(__UpperCamelCase , __UpperCamelCase )) __lowercase : List[Any] = [0] * dimension __lowercase : List[Any] = 1 return Vector(__UpperCamelCase ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): assert ( isinstance(__UpperCamelCase , __UpperCamelCase ) and isinstance(__UpperCamelCase , __UpperCamelCase ) and (isinstance(__UpperCamelCase , (int, float) )) ) return x * scalar + y def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): random.seed(__UpperCamelCase ) __lowercase : Any = [random.randint(__UpperCamelCase , __UpperCamelCase ) for _ in range(__UpperCamelCase )] return Vector(__UpperCamelCase ) class UpperCAmelCase_ : def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> None: __lowercase : List[Any] = matrix __lowercase : Optional[int] = w __lowercase : Union[str, Any] = h def __str__( self ) -> str: __lowercase : List[Any] = '''''' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , UpperCamelCase_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __lowercase : Any = [] for i in range(self.__height ): __lowercase : Tuple = [ self.__matrix[i][j] + other.component(UpperCamelCase_ , UpperCamelCase_ ) for j in range(self.__width ) ] matrix.append(UpperCamelCase_ ) return Matrix(UpperCamelCase_ , self.__width , self.__height ) else: raise Exception('''matrix must have the same dimension!''' ) def __sub__( self , UpperCamelCase_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __lowercase : Dict = [] for i in range(self.__height ): __lowercase : str = [ self.__matrix[i][j] - other.component(UpperCamelCase_ , UpperCamelCase_ ) for j in range(self.__width ) ] matrix.append(UpperCamelCase_ ) return Matrix(UpperCamelCase_ , self.__width , self.__height ) else: raise Exception('''matrices must have the same dimension!''' ) @overload def __mul__( self , UpperCamelCase_ ) -> Matrix: ... @overload def __mul__( self , UpperCamelCase_ ) -> Vector: ... def __mul__( self , UpperCamelCase_ ) -> Vector | Matrix: if isinstance(UpperCamelCase_ , UpperCamelCase_ ): # matrix-vector if len(UpperCamelCase_ ) == self.__width: __lowercase : str = zero_vector(self.__height ) for i in range(self.__height ): __lowercase : List[Any] = [ self.__matrix[i][j] * other.component(UpperCamelCase_ ) for j in range(self.__width ) ] ans.change_component(UpperCamelCase_ , sum(UpperCamelCase_ ) ) return ans else: raise Exception( '''vector must have the same size as the ''' '''number of columns of the matrix!''' ) elif isinstance(UpperCamelCase_ , (int, float) ): # matrix-scalar __lowercase : Any = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(UpperCamelCase_ , self.__width , self.__height ) return None def _lowerCamelCase ( self ) -> int: return self.__height def _lowerCamelCase ( self ) -> int: return self.__width def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('''change_component: indices out of bounds''' ) def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __lowercase : int = value else: raise Exception('''change_component: indices out of bounds''' ) def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> float: if self.__height != self.__width: raise Exception('''Matrix is not square''' ) __lowercase : Any = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(UpperCamelCase_ ) ): __lowercase : List[str] = minor[i][:y] + minor[i][y + 1 :] return Matrix(UpperCamelCase_ , self.__width - 1 , self.__height - 1 ).determinant() def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> float: if self.__height != self.__width: raise Exception('''Matrix is not square''' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(UpperCamelCase_ , UpperCamelCase_ ) else: raise Exception('''Indices out of bounds''' ) def _lowerCamelCase ( self ) -> float: if self.__height != self.__width: raise Exception('''Matrix is not square''' ) if self.__height < 1: raise Exception('''Matrix has no element''' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __lowercase : str = [ self.__matrix[0][y] * self.cofactor(0 , UpperCamelCase_ ) for y in range(self.__width ) ] return sum(UpperCamelCase_ ) def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : list[list[float]] = [[0] * n for _ in range(__UpperCamelCase )] return Matrix(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): random.seed(__UpperCamelCase ) __lowercase : list[list[float]] = [ [random.randint(__UpperCamelCase , __UpperCamelCase ) for _ in range(__UpperCamelCase )] for _ in range(__UpperCamelCase ) ] return Matrix(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
76
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """google/bit-50""": """https://huggingface.co/google/bit-50/resolve/main/config.json""", } class UpperCAmelCase ( __A , __A ): '''simple docstring''' lowerCamelCase_ = '''bit''' lowerCamelCase_ = ['''preactivation''', '''bottleneck'''] lowerCamelCase_ = ['''SAME''', '''VALID'''] def __init__( self , lowercase=3 , lowercase=6_4 , lowercase=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , lowercase=[3, 4, 6, 3] , lowercase="preactivation" , lowercase="relu" , lowercase=None , lowercase=3_2 , lowercase=0.0 , lowercase=False , lowercase=3_2 , lowercase=1 , lowercase=None , lowercase=None , **lowercase , ): """simple docstring""" super().__init__(**lowercase ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {','.join(self.layer_types )}''' ) if global_padding is not None: if global_padding.upper() in self.supported_padding: A_ : Tuple = global_padding.upper() else: raise ValueError(F'''Padding strategy {global_padding} not supported''' ) A_ : Any = num_channels A_ : Any = embedding_size A_ : List[Any] = hidden_sizes A_ : int = depths A_ : Union[str, Any] = layer_type A_ : List[Any] = hidden_act A_ : Tuple = global_padding A_ : List[str] = num_groups A_ : int = drop_path_rate A_ : str = embedding_dynamic_padding A_ : Dict = output_stride A_ : Any = width_factor A_ : int = ['stem'] + [F'''stage{idx}''' for idx in range(1 , len(lowercase ) + 1 )] A_ , A_ : List[Any] = get_aligned_output_features_output_indices( out_features=lowercase , out_indices=lowercase , stage_names=self.stage_names )
558
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a : int = logging.get_logger(__name__) a : str = {'vocab_file': 'sentencepiece.bpe.model'} a : Optional[int] = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } a : Optional[int] = { 'camembert-base': 512, } a : Union[str, Any] = '▁' class a ( _lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Union[str, Any] , lowercase_ : str , lowercase_ : str="<s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : Tuple="</s>" , lowercase_ : Tuple="<s>" , lowercase_ : Optional[int]="<unk>" , lowercase_ : int="<pad>" , lowercase_ : Dict="<mask>" , lowercase_ : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : List[str] , ): # Mask token behave like a normal word, i.e. include the space before it snake_case_ = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) else mask_token snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , mask_token=lowercase_ , additional_special_tokens=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowercase_ ) ) snake_case_ = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> snake_case_ = {'''<s>NOTUSED''': 0, '''<pad>''': 1, '''</s>NOTUSED''': 2, '''<unk>''': 3} snake_case_ = len(self.fairseq_tokens_to_ids ) snake_case_ = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def A_ ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_ ) if token_ids_a is None: return [1] + ([0] * len(lowercase_ )) + [1] return [1] + ([0] * len(lowercase_ )) + [1, 1] + ([0] * len(lowercase_ )) + [1] def A_ ( self : Dict , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None ): snake_case_ = [self.sep_token_id] snake_case_ = [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 A_ ( self : int ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def A_ ( self : str ): snake_case_ = {self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : List[str] , lowercase_ : str ): return self.sp_model.encode(lowercase_ , out_type=lowercase_ ) def A_ ( self : Any , lowercase_ : Optional[Any] ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(lowercase_ ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(lowercase_ ) def A_ ( self : Tuple , lowercase_ : List[str] ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def A_ ( self : Optional[int] , lowercase_ : Optional[int] ): snake_case_ = [] snake_case_ = '''''' snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(lowercase_ ) snake_case_ = False out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def __getstate__( self : Any ): snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Optional[Any] , lowercase_ : Optional[Any] ): snake_case_ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A_ ( self : Dict , lowercase_ : str , lowercase_ : Optional[str] = None ): if not os.path.isdir(lowercase_ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return snake_case_ = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase_ , '''wb''' ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
593
'''simple docstring''' import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated a : int = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ a : str = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def __magic_name__ ( __UpperCAmelCase ) -> Dict: '''simple docstring''' snake_case_ = numpy.dtype(numpy.uintaa ).newbyteorder('''>''' ) return numpy.frombuffer(bytestream.read(4 ), dtype=__UpperCAmelCase )[0] @deprecated(__UpperCAmelCase, '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __UpperCAmelCase ) -> List[Any]: '''simple docstring''' print('''Extracting''', f.name ) with gzip.GzipFile(fileobj=__UpperCAmelCase ) as bytestream: snake_case_ = _readaa(__UpperCAmelCase ) if magic != 2051: raise ValueError( '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) ) snake_case_ = _readaa(__UpperCAmelCase ) snake_case_ = _readaa(__UpperCAmelCase ) snake_case_ = _readaa(__UpperCAmelCase ) snake_case_ = bytestream.read(rows * cols * num_images ) snake_case_ = numpy.frombuffer(__UpperCAmelCase, dtype=numpy.uinta ) snake_case_ = data.reshape(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, 1 ) return data @deprecated(__UpperCAmelCase, '''Please use tf.one_hot on tensors.''' ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> List[str]: '''simple docstring''' snake_case_ = labels_dense.shape[0] snake_case_ = numpy.arange(__UpperCAmelCase ) * num_classes snake_case_ = numpy.zeros((num_labels, num_classes) ) snake_case_ = 1 return labels_one_hot @deprecated(__UpperCAmelCase, '''Please use tf.data to implement this functionality.''' ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase=False, __UpperCAmelCase=10 ) -> Dict: '''simple docstring''' print('''Extracting''', f.name ) with gzip.GzipFile(fileobj=__UpperCAmelCase ) as bytestream: snake_case_ = _readaa(__UpperCAmelCase ) if magic != 2049: raise ValueError( '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) ) snake_case_ = _readaa(__UpperCAmelCase ) snake_case_ = bytestream.read(__UpperCAmelCase ) snake_case_ = numpy.frombuffer(__UpperCAmelCase, dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__UpperCAmelCase, __UpperCAmelCase ) return labels class a : @deprecated( lowercase_ , '''Please use alternatives such as official/mnist/_DataSet.py''' ''' from tensorflow/models.''' , ) def __init__( self : List[str] , lowercase_ : Optional[Any] , lowercase_ : Any , lowercase_ : Tuple=False , lowercase_ : Tuple=False , lowercase_ : Optional[Any]=dtypes.floataa , lowercase_ : Any=True , lowercase_ : Optional[int]=None , ): snake_case_ ,snake_case_ = random_seed.get_seed(lowercase_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) snake_case_ = dtypes.as_dtype(lowercase_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype ) if fake_data: snake_case_ = 1_0000 snake_case_ = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F"images.shape: {images.shape} labels.shape: {labels.shape}" snake_case_ = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 snake_case_ = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. snake_case_ = images.astype(numpy.floataa ) snake_case_ = numpy.multiply(lowercase_ , 1.0 / 255.0 ) snake_case_ = images snake_case_ = labels snake_case_ = 0 snake_case_ = 0 @property def A_ ( self : int ): return self._images @property def A_ ( self : Tuple ): return self._labels @property def A_ ( self : str ): return self._num_examples @property def A_ ( self : List[str] ): return self._epochs_completed def A_ ( self : str , lowercase_ : List[str] , lowercase_ : Optional[int]=False , lowercase_ : Dict=True ): if fake_data: snake_case_ = [1] * 784 snake_case_ = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(lowercase_ )], [fake_label for _ in range(lowercase_ )], ) snake_case_ = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: snake_case_ = numpy.arange(self._num_examples ) numpy.random.shuffle(lowercase_ ) snake_case_ = self.images[perma] snake_case_ = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch snake_case_ = self._num_examples - start snake_case_ = self._images[start : self._num_examples] snake_case_ = self._labels[start : self._num_examples] # Shuffle the data if shuffle: snake_case_ = numpy.arange(self._num_examples ) numpy.random.shuffle(lowercase_ ) snake_case_ = self.images[perm] snake_case_ = self.labels[perm] # Start next epoch snake_case_ = 0 snake_case_ = batch_size - rest_num_examples snake_case_ = self._index_in_epoch snake_case_ = self._images[start:end] snake_case_ = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size snake_case_ = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__UpperCAmelCase, '''Please write your own downloading logic.''' ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> Any: '''simple docstring''' if not gfile.Exists(__UpperCAmelCase ): gfile.MakeDirs(__UpperCAmelCase ) snake_case_ = os.path.join(__UpperCAmelCase, __UpperCAmelCase ) if not gfile.Exists(__UpperCAmelCase ): urllib.request.urlretrieve(__UpperCAmelCase, __UpperCAmelCase ) # noqa: S310 with gfile.GFile(__UpperCAmelCase ) as f: snake_case_ = f.size() print('''Successfully downloaded''', __UpperCAmelCase, __UpperCAmelCase, '''bytes.''' ) return filepath @deprecated( __UpperCAmelCase, '''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase=False, __UpperCAmelCase=False, __UpperCAmelCase=dtypes.floataa, __UpperCAmelCase=True, __UpperCAmelCase=5000, __UpperCAmelCase=None, __UpperCAmelCase=DEFAULT_SOURCE_URL, ) -> Tuple: '''simple docstring''' if fake_data: def fake(): return _DataSet( [], [], fake_data=__UpperCAmelCase, one_hot=__UpperCAmelCase, dtype=__UpperCAmelCase, seed=__UpperCAmelCase ) snake_case_ = fake() snake_case_ = fake() snake_case_ = fake() return _Datasets(train=__UpperCAmelCase, validation=__UpperCAmelCase, test=__UpperCAmelCase ) if not source_url: # empty string check snake_case_ = DEFAULT_SOURCE_URL snake_case_ = '''train-images-idx3-ubyte.gz''' snake_case_ = '''train-labels-idx1-ubyte.gz''' snake_case_ = '''t10k-images-idx3-ubyte.gz''' snake_case_ = '''t10k-labels-idx1-ubyte.gz''' snake_case_ = _maybe_download( __UpperCAmelCase, __UpperCAmelCase, source_url + train_images_file ) with gfile.Open(__UpperCAmelCase, '''rb''' ) as f: snake_case_ = _extract_images(__UpperCAmelCase ) snake_case_ = _maybe_download( __UpperCAmelCase, __UpperCAmelCase, source_url + train_labels_file ) with gfile.Open(__UpperCAmelCase, '''rb''' ) as f: snake_case_ = _extract_labels(__UpperCAmelCase, one_hot=__UpperCAmelCase ) snake_case_ = _maybe_download( __UpperCAmelCase, __UpperCAmelCase, source_url + test_images_file ) with gfile.Open(__UpperCAmelCase, '''rb''' ) as f: snake_case_ = _extract_images(__UpperCAmelCase ) snake_case_ = _maybe_download( __UpperCAmelCase, __UpperCAmelCase, source_url + test_labels_file ) with gfile.Open(__UpperCAmelCase, '''rb''' ) as f: snake_case_ = _extract_labels(__UpperCAmelCase, one_hot=__UpperCAmelCase ) if not 0 <= validation_size <= len(__UpperCAmelCase ): snake_case_ = ( '''Validation size should be between 0 and ''' F"{len(__UpperCAmelCase )}. Received: {validation_size}." ) raise ValueError(__UpperCAmelCase ) snake_case_ = train_images[:validation_size] snake_case_ = train_labels[:validation_size] snake_case_ = train_images[validation_size:] snake_case_ = train_labels[validation_size:] snake_case_ = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} snake_case_ = _DataSet(__UpperCAmelCase, __UpperCAmelCase, **__UpperCAmelCase ) snake_case_ = _DataSet(__UpperCAmelCase, __UpperCAmelCase, **__UpperCAmelCase ) snake_case_ = _DataSet(__UpperCAmelCase, __UpperCAmelCase, **__UpperCAmelCase ) return _Datasets(train=__UpperCAmelCase, validation=__UpperCAmelCase, test=__UpperCAmelCase )
593
1
'''simple docstring''' import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class UpperCAmelCase_ (_UpperCAmelCase ): """simple docstring""" lowerCamelCase : torch.FloatTensor lowerCamelCase : Optional[torch.FloatTensor] = None def UpperCAmelCase__ ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any]=0.999 , UpperCAmelCase_ : Tuple="cosine" , ) -> Optional[Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(UpperCAmelCase_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(UpperCAmelCase_ : Tuple ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) __lowerCamelCase : List[str] = [] for i in range(UpperCAmelCase_ ): __lowerCamelCase : int = i / num_diffusion_timesteps __lowerCamelCase : List[str] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(UpperCAmelCase_ ) / alpha_bar_fn(UpperCAmelCase_ ) , UpperCAmelCase_ ) ) return torch.tensor(UpperCAmelCase_ , dtype=torch.floataa ) class UpperCAmelCase_ (_UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" @register_to_config def __init__( self , SCREAMING_SNAKE_CASE_ = 10_00 , SCREAMING_SNAKE_CASE_ = "fixed_small_log" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = "epsilon" , SCREAMING_SNAKE_CASE_ = "squaredcos_cap_v2" , ) -> List[str]: if beta_schedule != "squaredcos_cap_v2": raise ValueError('UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'' ) __lowerCamelCase : Optional[Any] = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : str = 1.0 - self.betas __lowerCamelCase : Union[str, Any] = torch.cumprod(self.alphas , dim=0 ) __lowerCamelCase : Optional[Any] = torch.tensor(1.0 ) # standard deviation of the initial noise distribution __lowerCamelCase : Optional[Any] = 1.0 # setable values __lowerCamelCase : Optional[Any] = None __lowerCamelCase : Optional[int] = torch.from_numpy(np.arange(0 , SCREAMING_SNAKE_CASE_ )[::-1].copy() ) __lowerCamelCase : Optional[int] = variance_type def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> torch.FloatTensor: return sample def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Optional[int]: __lowerCamelCase : Optional[int] = num_inference_steps __lowerCamelCase : Any = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) __lowerCamelCase : str = (np.arange(0 , SCREAMING_SNAKE_CASE_ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) __lowerCamelCase : List[str] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ) -> Dict: if prev_timestep is None: __lowerCamelCase : Dict = t - 1 __lowerCamelCase : int = self.alphas_cumprod[t] __lowerCamelCase : str = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __lowerCamelCase : Optional[int] = 1 - alpha_prod_t __lowerCamelCase : Dict = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __lowerCamelCase : List[str] = self.betas[t] else: __lowerCamelCase : List[str] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample __lowerCamelCase : List[str] = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: __lowerCamelCase : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": __lowerCamelCase : Optional[Any] = torch.log(torch.clamp(SCREAMING_SNAKE_CASE_ , min=1E-20 ) ) __lowerCamelCase : List[Any] = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler __lowerCamelCase : str = variance.log() __lowerCamelCase : Dict = beta.log() __lowerCamelCase : List[str] = (predicted_variance + 1) / 2 __lowerCamelCase : str = frac * max_log + (1 - frac) * min_log return variance def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ) -> Union[UnCLIPSchedulerOutput, Tuple]: __lowerCamelCase : List[str] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": __lowerCamelCase , __lowerCamelCase : List[Any] = torch.split(SCREAMING_SNAKE_CASE_ , sample.shape[1] , dim=1 ) else: __lowerCamelCase : Optional[int] = None # 1. compute alphas, betas if prev_timestep is None: __lowerCamelCase : str = t - 1 __lowerCamelCase : int = self.alphas_cumprod[t] __lowerCamelCase : Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __lowerCamelCase : int = 1 - alpha_prod_t __lowerCamelCase : List[Any] = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __lowerCamelCase : Dict = self.betas[t] __lowerCamelCase : List[Any] = self.alphas[t] else: __lowerCamelCase : Optional[Any] = 1 - alpha_prod_t / alpha_prod_t_prev __lowerCamelCase : Dict = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": __lowerCamelCase : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": __lowerCamelCase : Optional[Any] = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`' ' for the UnCLIPScheduler.' ) # 3. Clip "predicted x_0" if self.config.clip_sample: __lowerCamelCase : Dict = torch.clamp( SCREAMING_SNAKE_CASE_ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __lowerCamelCase : Any = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t __lowerCamelCase : Optional[int] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __lowerCamelCase : Union[str, Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise __lowerCamelCase : Dict = 0 if t > 0: __lowerCamelCase : Union[str, Any] = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=SCREAMING_SNAKE_CASE_ , device=model_output.device ) __lowerCamelCase : Union[str, Any] = self._get_variance( SCREAMING_SNAKE_CASE_ , predicted_variance=SCREAMING_SNAKE_CASE_ , prev_timestep=SCREAMING_SNAKE_CASE_ , ) if self.variance_type == "fixed_small_log": __lowerCamelCase : Optional[Any] = variance elif self.variance_type == "learned_range": __lowerCamelCase : Tuple = (0.5 * variance).exp() else: raise ValueError( f'variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`' ' for the UnCLIPScheduler.' ) __lowerCamelCase : Tuple = variance * variance_noise __lowerCamelCase : List[str] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_ , pred_original_sample=SCREAMING_SNAKE_CASE_ ) def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> torch.FloatTensor: # Make sure alphas_cumprod and timestep have same device and dtype as original_samples __lowerCamelCase : str = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) __lowerCamelCase : Any = timesteps.to(original_samples.device ) __lowerCamelCase : Tuple = alphas_cumprod[timesteps] ** 0.5 __lowerCamelCase : List[Any] = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): __lowerCamelCase : Union[str, Any] = sqrt_alpha_prod.unsqueeze(-1 ) __lowerCamelCase : Optional[Any] = (1 - alphas_cumprod[timesteps]) ** 0.5 __lowerCamelCase : Tuple = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): __lowerCamelCase : str = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) __lowerCamelCase : str = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
13
'''simple docstring''' from __future__ import annotations import os from collections.abc import Mapping A__ : Optional[Any] = tuple[int, int] class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: __lowerCamelCase : set[int] = vertices __lowerCamelCase : dict[EdgeT, int] = { (min(SCREAMING_SNAKE_CASE_ ), max(SCREAMING_SNAKE_CASE_ )): weight for edge, weight in edges.items() } def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) __lowerCamelCase : Union[str, Any] = weight def lowercase_ ( self ) -> Graph: __lowerCamelCase : Graph = Graph({min(self.vertices )} , {} ) __lowerCamelCase : EdgeT __lowerCamelCase : int __lowerCamelCase : EdgeT __lowerCamelCase : int while len(subgraph.vertices ) < len(self.vertices ): __lowerCamelCase : Any = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: __lowerCamelCase : Optional[int] = edge __lowerCamelCase : List[str] = weight subgraph.add_edge(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return subgraph def UpperCAmelCase__ ( UpperCAmelCase_ : str = "p107_network.txt" ) -> int: __lowerCamelCase : str = os.path.abspath(os.path.dirname(UpperCAmelCase_ ) ) __lowerCamelCase : str = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) __lowerCamelCase : dict[EdgeT, int] = {} __lowerCamelCase : list[str] __lowerCamelCase : int __lowerCamelCase : int with open(UpperCAmelCase_ ) as f: __lowerCamelCase : Any = f.read().strip().split('\n' ) __lowerCamelCase : Any = [line.split(',' ) for line in data] for edgea in range(1 , len(UpperCAmelCase_ ) ): for edgea in range(UpperCAmelCase_ ): if adjaceny_matrix[edgea][edgea] != "-": __lowerCamelCase : int = int(adjaceny_matrix[edgea][edgea] ) __lowerCamelCase : Graph = Graph(set(range(len(UpperCAmelCase_ ) ) ) , UpperCAmelCase_ ) __lowerCamelCase : Graph = graph.prims_algorithm() __lowerCamelCase : int = sum(graph.edges.values() ) __lowerCamelCase : int = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(f'''{solution() = }''')
13
1
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[list[int]] ): def update_area_of_max_square(_lowerCamelCase : int , _lowerCamelCase : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 __a : Optional[int] = update_area_of_max_square(_lowerCamelCase , col + 1 ) __a : Optional[Any] = update_area_of_max_square(row + 1 , col + 1 ) __a : Optional[Any] = update_area_of_max_square(row + 1 , _lowerCamelCase ) if mat[row][col]: __a : str = 1 + min([right, diagonal, down] ) __a : List[str] = max(largest_square_area[0] , _lowerCamelCase ) return sub_problem_sol else: return 0 __a : List[Any] = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[list[int]] ): def update_area_of_max_square_using_dp_array( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] __a : Optional[int] = update_area_of_max_square_using_dp_array(_lowerCamelCase , col + 1 , _lowerCamelCase ) __a : int = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , _lowerCamelCase ) __a : Any = update_area_of_max_square_using_dp_array(row + 1 , _lowerCamelCase , _lowerCamelCase ) if mat[row][col]: __a : Any = 1 + min([right, diagonal, down] ) __a : str = max(largest_square_area[0] , _lowerCamelCase ) __a : Dict = sub_problem_sol return sub_problem_sol else: return 0 __a : List[str] = [0] __a : Tuple = [[-1] * cols for _ in range(_lowerCamelCase )] update_area_of_max_square_using_dp_array(0 , 0 , _lowerCamelCase ) return largest_square_area[0] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[list[int]] ): __a : Optional[Any] = [[0] * (cols + 1) for _ in range(rows + 1 )] __a : List[Any] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __a : int = dp_array[row][col + 1] __a : List[str] = dp_array[row + 1][col + 1] __a : Union[str, Any] = dp_array[row + 1][col] if mat[row][col] == 1: __a : Any = 1 + min(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Tuple = max(dp_array[row][col] , _lowerCamelCase ) else: __a : Optional[Any] = 0 return largest_square_area def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[list[int]] ): __a : Optional[int] = [0] * (cols + 1) __a : int = [0] * (cols + 1) __a : Tuple = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __a : Tuple = current_row[col + 1] __a : Tuple = next_row[col + 1] __a : List[str] = next_row[col] if mat[row][col] == 1: __a : Any = 1 + min(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Tuple = max(current_row[col] , _lowerCamelCase ) else: __a : Any = 0 __a : int = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
63
"""simple docstring""" import unittest from knapsack import knapsack as k class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : str = 0 __a : Optional[Any] = [0] __a : int = [0] __a : str = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) __a : int = [60] __a : Union[str, Any] = [10] __a : Tuple = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = 3 __a : str = [1, 2, 3] __a : Optional[Any] = [3, 2, 1] __a : int = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 5 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = 50 __a : Tuple = [60, 100, 120] __a : List[str] = [10, 20, 30] __a : Union[str, Any] = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 220 ) if __name__ == "__main__": unittest.main()
63
1
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class _UpperCamelCase ( SCREAMING_SNAKE_CASE): '''simple docstring''' _snake_case = '''M-CLIP''' def __init__( self , a_=1_0_2_4 , a_=7_6_8 , **a_ ) -> Tuple: lowercase : int = transformerDimSize lowercase : List[str] = imageDimSize super().__init__(**a_ ) class _UpperCamelCase ( SCREAMING_SNAKE_CASE): '''simple docstring''' _snake_case = MCLIPConfig def __init__( self , a_ , *a_ , **a_ ) -> List[Any]: super().__init__(a_ , *a_ , **a_ ) lowercase : Any = XLMRobertaModel(a_ ) lowercase : int = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def a__ ( self , a_ , a_ ) -> Any: lowercase : Any = self.transformer(input_ids=a_ , attention_mask=a_ )[0] lowercase : List[Any] = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(a_ ), embs
372
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image lowerCAmelCase : List[Any] = ["""text""", """image""", """audio"""] def _A ( A ) -> Dict: lowercase : str = [] for input_type in input_types: if input_type == "text": inputs.append("Text input" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" ).resize((5_1_2, 5_1_2) ) ) elif input_type == "audio": inputs.append(torch.ones(3_0_0_0 ) ) elif isinstance(A ,A ): inputs.append(create_inputs(A ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def _A ( A ) -> str: lowercase : Tuple = [] for output in outputs: if isinstance(A ,(str, AgentText) ): output_types.append("text" ) elif isinstance(A ,(Image.Image, AgentImage) ): output_types.append("image" ) elif isinstance(A ,(torch.Tensor, AgentAudio) ): output_types.append("audio" ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class _UpperCamelCase : '''simple docstring''' def a__ ( self ) -> Optional[Any]: self.assertTrue(hasattr(self.tool , "inputs" ) ) self.assertTrue(hasattr(self.tool , "outputs" ) ) lowercase : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , a_ ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase : Any = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def a__ ( self ) -> Any: lowercase : Any = create_inputs(self.tool.inputs ) lowercase : Tuple = self.tool(*a_ ) # There is a single output if len(self.tool.outputs ) == 1: lowercase : Any = [outputs] self.assertListEqual(output_types(a_ ) , self.tool.outputs ) def a__ ( self ) -> List[str]: self.assertTrue(hasattr(self.tool , "description" ) ) self.assertTrue(hasattr(self.tool , "default_checkpoint" ) ) self.assertTrue(self.tool.description.startswith("This is a tool that" ) ) def a__ ( self ) -> int: lowercase : str = create_inputs(self.tool.inputs ) lowercase : str = self.tool(*a_ ) if not isinstance(a_ , a_ ): lowercase : Union[str, Any] = [outputs] self.assertEqual(len(a_ ) , len(self.tool.outputs ) ) for output, output_type in zip(a_ , self.tool.outputs ): lowercase : List[str] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(a_ , a_ ) ) def a__ ( self ) -> Optional[int]: lowercase : int = create_inputs(self.tool.inputs ) lowercase : str = [] for _input, input_type in zip(a_ , self.tool.inputs ): if isinstance(a_ , a_ ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase : Optional[int] = self.tool(*a_ ) if not isinstance(a_ , a_ ): lowercase : str = [outputs] self.assertEqual(len(a_ ) , len(self.tool.outputs ) )
372
1
import os def _lowerCAmelCase ( __lowerCAmelCase ) -> List[Any]: """simple docstring""" snake_case__ : Dict = len(grid[0] ) snake_case__ : Optional[Any] = len(__lowerCAmelCase ) snake_case__ : int = 0 snake_case__ : List[str] = 0 snake_case__ : Optional[Any] = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(__lowerCAmelCase ): for j in range(n_rows - 3 ): snake_case__ : int = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] snake_case__ : Optional[int] = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: snake_case__ : Any = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: snake_case__ : str = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) snake_case__ : Union[str, Any] = max( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if max_product > largest: snake_case__ : List[Any] = max_product return largest def _lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" snake_case__ : Any = [] with open(os.path.dirname(__lowerCAmelCase ) + '''/grid.txt''' ) as file: for line in file: grid.append(line.strip('''\n''' ).split(''' ''' ) ) snake_case__ : Optional[Any] = [[int(__lowerCAmelCase ) for i in grid[j]] for j in range(len(__lowerCAmelCase ) )] return largest_product(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
219
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> Dict: """simple docstring""" if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer snake_case__ : Any = flax_key_tuple[:-1] + ('''weight''',) snake_case__ : Tuple = torch.permute(__lowerCAmelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCAmelCase ): # linear layer snake_case__ : Optional[int] = flax_key_tuple[:-1] + ('''weight''',) snake_case__ : Union[str, Any] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: snake_case__ : Union[str, Any] = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: """simple docstring""" if "metadata" in layer: snake_case__ : Union[str, Any] = layer.split('''metadata''' ) snake_case__ : Dict = ''''''.join(split_layer[0] )[:-1] snake_case__ : str = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: snake_case__ : Tuple = layer.split('''kvstore''' ) snake_case__ : int = ''''''.join(split_layer[0] )[:-1] snake_case__ : Union[str, Any] = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: snake_case__ : Union[str, Any] = layer.split('''/''' ) snake_case__ : List[str] = '''/'''.join(split_layer[:-1] ) snake_case__ : Optional[Any] = (split_layer[-1],) if "kvstore/path" in layer: snake_case__ : Any = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: snake_case__ : Any = '''file''' else: snake_case__ : int = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: """simple docstring""" snake_case__ : str = rename_keys(__lowerCAmelCase ) snake_case__ : List[str] = {} for k, v in current_block.items(): snake_case__ : List[str] = v snake_case__ : Any = new_current_block torch.save(__lowerCAmelCase , __lowerCAmelCase ) def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = WEIGHTS_NAME ) -> Union[str, Any]: """simple docstring""" snake_case__ : Tuple = convert_file_size_to_int(__lowerCAmelCase ) snake_case__ : Optional[int] = [] snake_case__ : Any = {} snake_case__ : Any = 0 snake_case__ : List[str] = 0 os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: snake_case__ : Optional[int] = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] snake_case__ : List[str] = flatten_dict(__lowerCAmelCase , sep='''/''' ) snake_case__ : Optional[Any] = {} for layer in checkpoint_info.keys(): snake_case__ , snake_case__ , snake_case__ : Any = get_key_and_tensorstore_dict( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if curr_real_layer_name in all_layers: snake_case__ : List[Any] = content else: snake_case__ : Tuple = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file snake_case__ : Any = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() snake_case__ : str = torch.tensor(__lowerCAmelCase ) snake_case__ : List[Any] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts snake_case__ , snake_case__ : Optional[int] = rename_base_flax_keys(tuple(key.split('''/''' ) ) , __lowerCAmelCase ) snake_case__ : List[str] = '''/'''.join(__lowerCAmelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: snake_case__ : Optional[int] = os.path.join( __lowerCAmelCase , weights_name.replace('''.bin''' , f"""-{len(__lowerCAmelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(__lowerCAmelCase , __lowerCAmelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block snake_case__ : List[str] = {} snake_case__ : str = 0 snake_case__ : int = raw_weights.to(getattr(__lowerCAmelCase , __lowerCAmelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block snake_case__ : int = os.path.join(__lowerCAmelCase , weights_name.replace('''.bin''' , f"""-{len(__lowerCAmelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(__lowerCAmelCase , __lowerCAmelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__lowerCAmelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index snake_case__ : Optional[Any] = {} snake_case__ : List[Any] = {} for idx, shard in enumerate(__lowerCAmelCase ): snake_case__ : List[Any] = weights_name.replace( '''.bin''' , f"""-{idx+1:05d}-of-{len(__lowerCAmelCase ):05d}.bin""" ) # len(sharded_state_dicts):05d} snake_case__ : List[Any] = os.path.join(__lowerCAmelCase , weights_name.replace('''.bin''' , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(__lowerCAmelCase , os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) snake_case__ : Optional[Any] = shard for key in shard: snake_case__ : int = shard_file # Add the metadata snake_case__ : int = {'''total_size''': total_size} snake_case__ : Dict = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) , '''w''' , encoding='''utf-8''' ) as f: snake_case__ : Optional[Any] = json.dumps(__lowerCAmelCase , indent=2 , sort_keys=__lowerCAmelCase ) + '''\n''' f.write(__lowerCAmelCase ) return metadata, index if __name__ == "__main__": A__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--switch_t5x_checkpoint_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600''', type=str, required=False, help='''Path to a directory containing a folder per layer. Follows the original Google format.''', ) parser.add_argument('''--max_shard_size''', default='''10GB''', required=False, help='''Max shard size''') parser.add_argument('''--dtype''', default='''bfloat16''', type=str, required=False, help='''dtype of the saved model''') parser.add_argument( '''--pytorch_dump_folder_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted''', type=str, required=False, help='''Path to the output pytorch model.''', ) A__ = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def _lowerCAmelCase ( ) -> List[Any]: """simple docstring""" from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer snake_case__ : Dict = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) snake_case__ : Tuple = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) snake_case__ : Any = TaTokenizer.from_pretrained('''t5-small''' ) snake_case__ : List[str] = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' snake_case__ : Any = tokenizer(__lowerCAmelCase , return_tensors='''pt''' ).input_ids snake_case__ : Dict = model.generate(__lowerCAmelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
219
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 _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__(self : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str]=7 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : int=18 , UpperCAmelCase_ : str=30 , UpperCAmelCase_ : Dict=400 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Union[str, Any]=True , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =size if size is not None else {"height": 18, "width": 18} lowerCamelCase__: Tuple =parent lowerCamelCase__: Dict =batch_size lowerCamelCase__: Optional[Any] =num_channels lowerCamelCase__: Union[str, Any] =image_size lowerCamelCase__: Dict =min_resolution lowerCamelCase__: int =max_resolution lowerCamelCase__: Tuple =do_resize lowerCamelCase__: Tuple =size lowerCamelCase__: Dict =do_normalize def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Union[str, Any]: '''simple docstring''' return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866_4436_3403_3203, 0.6618_8293_6954_4983, 0.3891_7464_0178_6804], [-0.6042_5591_4688_1104, -0.0_2295_0088_6052_8469, 0.5423_7973_6900_3296], ]), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = ImageGPTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ (self : Dict) ->Any: '''simple docstring''' lowerCamelCase__: int =ImageGPTImageProcessingTester(self) @property def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__: List[str] =self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(UpperCAmelCase_ , "clusters")) self.assertTrue(hasattr(UpperCAmelCase_ , "do_resize")) self.assertTrue(hasattr(UpperCAmelCase_ , "size")) self.assertTrue(hasattr(UpperCAmelCase_ , "do_normalize")) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any =self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {"height": 18, "width": 18}) lowerCamelCase__: Optional[Any] =self.image_processing_class.from_dict(self.image_processor_dict , size=42) self.assertEqual(image_processor.size , {"height": 42, "width": 42}) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.image_processing_class(**self.image_processor_dict) lowerCamelCase__: str =json.loads(image_processor.to_json_string()) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key])) else: self.assertEqual(obj[key] , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' lowerCamelCase__: List[str] =self.image_processing_class(**self.image_processor_dict) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase__: Any =os.path.join(UpperCAmelCase_ , "image_processor.json") image_processor_first.to_json_file(UpperCAmelCase_) lowerCamelCase__: Tuple =self.image_processing_class.from_json_file(UpperCAmelCase_).to_dict() lowerCamelCase__: Optional[Any] =image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key])) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Dict: '''simple docstring''' lowerCamelCase__: List[Any] =self.image_processing_class(**self.image_processor_dict) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =self.image_processing_class.from_pretrained(UpperCAmelCase_).to_dict() lowerCamelCase__: Tuple =image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key])) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_) @unittest.skip("ImageGPT requires clusters at initialization") def SCREAMING_SNAKE_CASE_ (self : int) ->int: '''simple docstring''' pass def lowerCAmelCase_ ( ) -> Dict: """simple docstring""" lowerCamelCase__: Optional[int] =load_dataset("hf-internal-testing/fixtures_image_utils" , split="test" ) lowerCamelCase__: Union[str, Any] =Image.open(dataset[4]["file"] ) lowerCamelCase__: int =Image.open(dataset[5]["file"] ) lowerCamelCase__: List[Any] =[imagea, imagea] return images @require_vision @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[str] =ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small") lowerCamelCase__: List[str] =prepare_images() # test non-batched lowerCamelCase__: Optional[int] =image_processing(images[0] , return_tensors="pt") self.assertIsInstance(encoding.input_ids , torch.LongTensor) self.assertEqual(encoding.input_ids.shape , (1, 1_024)) lowerCamelCase__: Optional[int] =[306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_) # test batched lowerCamelCase__: str =image_processing(UpperCAmelCase_ , return_tensors="pt") self.assertIsInstance(encoding.input_ids , torch.LongTensor) self.assertEqual(encoding.input_ids.shape , (2, 1_024)) lowerCamelCase__: Union[str, Any] =[303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_)
59
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process snake_case_ : str = logging.getLogger(__name__) def lowerCamelCase( a__ ,a__): return (preds == labels).mean() @dataclass class A__ : UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class A__ : UpperCAmelCase = field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys() )} ) UpperCAmelCase = field(metadata={"help": "Should contain the data files for the task."} ) UpperCAmelCase = field( default=128 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCAmelCase = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def lowerCamelCase( ): # 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 =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use" ''' --overwrite_output_dir to overcome.''') # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' ,datefmt='''%m/%d/%Y %H:%M:%S''' ,level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN ,) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' ,training_args.local_rank ,training_args.device ,training_args.n_gpu ,bool(training_args.local_rank != -1) ,training_args.fpaa ,) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' ,a__) # Set seed set_seed(training_args.seed) try: _SCREAMING_SNAKE_CASE =processors[data_args.task_name]() _SCREAMING_SNAKE_CASE =processor.get_labels() _SCREAMING_SNAKE_CASE =len(a__) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name)) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path ,num_labels=a__ ,finetuning_task=data_args.task_name ,cache_dir=model_args.cache_dir ,) _SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,cache_dir=model_args.cache_dir ,) _SCREAMING_SNAKE_CASE =AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path ,from_tf=bool('''.ckpt''' in model_args.model_name_or_path) ,config=a__ ,cache_dir=model_args.cache_dir ,) # Get datasets _SCREAMING_SNAKE_CASE =( MultipleChoiceDataset( data_dir=data_args.data_dir ,tokenizer=a__ ,task=data_args.task_name ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.train ,) if training_args.do_train else None ) _SCREAMING_SNAKE_CASE =( MultipleChoiceDataset( data_dir=data_args.data_dir ,tokenizer=a__ ,task=data_args.task_name ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.dev ,) if training_args.do_eval else None ) def compute_metrics(a__) -> Dict: _SCREAMING_SNAKE_CASE =np.argmax(p.predictions ,axis=1) return {"acc": simple_accuracy(a__ ,p.label_ids)} # Data collator _SCREAMING_SNAKE_CASE =DataCollatorWithPadding(a__ ,pad_to_multiple_of=8) if training_args.fpaa else None # Initialize our Trainer _SCREAMING_SNAKE_CASE =Trainer( model=a__ ,args=a__ ,train_dataset=a__ ,eval_dataset=a__ ,compute_metrics=a__ ,data_collator=a__ ,) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir) # Evaluation _SCREAMING_SNAKE_CASE ={} if training_args.do_eval: logger.info('''*** Evaluate ***''') _SCREAMING_SNAKE_CASE =trainer.evaluate() _SCREAMING_SNAKE_CASE =os.path.join(training_args.output_dir ,'''eval_results.txt''') if trainer.is_world_master(): with open(a__ ,'''w''') as writer: logger.info('''***** Eval results *****''') for key, value in result.items(): logger.info(''' %s = %s''' ,a__ ,a__) writer.write('''%s = %s\n''' % (key, value)) results.update(a__) return results def lowerCamelCase( a__): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
691
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer _SCREAMING_SNAKE_CASE = ["gpt2"] _SCREAMING_SNAKE_CASE = "gpt2" if is_tf_available(): class lowerCAmelCase_ ( tf.Module ): def __init__( self , _lowerCAmelCase ) -> str: super().__init__() _lowerCAmelCase = tokenizer _lowerCAmelCase = AutoConfig.from_pretrained(_lowerCAmelCase ) _lowerCAmelCase = TFGPTaLMHeadModel.from_config(_lowerCAmelCase ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name="text" ),) ) def _snake_case ( self , _lowerCAmelCase ) -> Tuple: _lowerCAmelCase = self.tokenizer(_lowerCAmelCase ) _lowerCAmelCase = tokenized["input_ids"].to_tensor() _lowerCAmelCase = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) _lowerCAmelCase = self.model(input_ids=_lowerCAmelCase , attention_mask=_lowerCAmelCase )["logits"] return outputs @require_tf @require_keras_nlp class lowerCAmelCase_ ( unittest.TestCase ): def _snake_case ( self ) -> List[Any]: super().setUp() _lowerCAmelCase = [GPTaTokenizer.from_pretrained(_lowerCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS)] _lowerCAmelCase = [TFGPTaTokenizer.from_pretrained(_lowerCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) _lowerCAmelCase = [ "This is a straightforward English test sentence.", "This one has some weird characters\rto\nsee\r\nif those\u00E9break things.", "Now we're going to add some Chinese: 一 二 三 一二三", "And some much more rare Chinese: 齉 堃 齉堃", "Je vais aussi écrire en français pour tester les accents", "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ", ] _lowerCAmelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _snake_case ( self ) -> Dict: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: _lowerCAmelCase = tokenizer([test_inputs] , return_tensors="tf" ) _lowerCAmelCase = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors _lowerCAmelCase = python_outputs[key].numpy() _lowerCAmelCase = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(_lowerCAmelCase , tf.intaa ) == tf_outputs_values ) ) @slow def _snake_case ( self ) -> Dict: for tf_tokenizer in self.tf_tokenizers: _lowerCAmelCase = tf.function(_lowerCAmelCase ) for test_inputs in self.test_sentences: _lowerCAmelCase = tf.constant(_lowerCAmelCase ) _lowerCAmelCase = compiled_tokenizer(_lowerCAmelCase ) _lowerCAmelCase = tf_tokenizer(_lowerCAmelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _snake_case ( self ) -> Any: for tf_tokenizer in self.tf_tokenizers: _lowerCAmelCase = ModelToSave(tokenizer=_lowerCAmelCase ) _lowerCAmelCase = tf.convert_to_tensor([self.test_sentences[0]] ) _lowerCAmelCase = model.serving(_lowerCAmelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: _lowerCAmelCase = Path(_lowerCAmelCase ) / "saved.model" tf.saved_model.save(_lowerCAmelCase , _lowerCAmelCase , signatures={"serving_default": model.serving} ) _lowerCAmelCase = tf.saved_model.load(_lowerCAmelCase ) _lowerCAmelCase = loaded_model.signatures["serving_default"](_lowerCAmelCase )["output_0"] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def _snake_case ( self ) -> Dict: for tf_tokenizer in self.tf_tokenizers: _lowerCAmelCase = tf.convert_to_tensor([self.test_sentences[0]] ) _lowerCAmelCase = tf_tokenizer(_lowerCAmelCase ) # Build model with some sample inputs _lowerCAmelCase = tf_tokenizer.get_config() _lowerCAmelCase = TFGPTaTokenizer.from_config(_lowerCAmelCase ) _lowerCAmelCase = model_from_config(_lowerCAmelCase ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def _snake_case ( self ) -> str: for tf_tokenizer in self.tf_tokenizers: # for the test to run _lowerCAmelCase = 123123 for max_length in [3, 5, 1024]: _lowerCAmelCase = tf.convert_to_tensor([self.test_sentences[0]] ) _lowerCAmelCase = tf_tokenizer(_lowerCAmelCase , max_length=_lowerCAmelCase ) _lowerCAmelCase = out["input_ids"].numpy().shape[1] assert out_length == max_length
489
'''simple docstring''' import math def __a(SCREAMING_SNAKE_CASE_ : int = 100 ): '''simple docstring''' _lowerCAmelCase = sum(i * i for i in range(1 , n + 1 ) ) _lowerCAmelCase = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f'''{solution() = }''')
489
1
"""simple docstring""" import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} # See all BART models at https://huggingface.co/models?filter=bart SCREAMING_SNAKE_CASE_ = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, } SCREAMING_SNAKE_CASE_ = { 'facebook/bart-base': 1024, 'facebook/bart-large': 1024, 'facebook/bart-large-mnli': 1024, 'facebook/bart-large-cnn': 1024, 'facebook/bart-large-xsum': 1024, 'yjernite/bart_eli5': 1024, } @lru_cache() def __snake_case ( ): """simple docstring""" UpperCamelCase = ( list(range(ord('''!''' ) ,ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) ,ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) ,ord('''ÿ''' ) + 1 ) ) ) UpperCamelCase = bs[:] UpperCamelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(_lowercase ) cs.append(2**8 + n ) n += 1 UpperCamelCase = [chr(_lowercase ) for n in cs] return dict(zip(_lowercase ,_lowercase ) ) def __snake_case ( _lowercase ): """simple docstring""" UpperCamelCase = set() UpperCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCamelCase = char return pairs class snake_case_ ( lowerCamelCase_ ): """simple docstring""" A_ = VOCAB_FILES_NAMES A_ = PRETRAINED_VOCAB_FILES_MAP A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ = ['''input_ids''', '''attention_mask'''] def __init__( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_="replace" , lowerCamelCase_="<s>" , lowerCamelCase_="</s>" , lowerCamelCase_="</s>" , lowerCamelCase_="<s>" , lowerCamelCase_="<unk>" , lowerCamelCase_="<pad>" , lowerCamelCase_="<mask>" , lowerCamelCase_=False , **lowerCamelCase_ , ) -> Dict: UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else bos_token UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else eos_token UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else sep_token UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else cls_token UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else unk_token UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else mask_token super().__init__( errors=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , add_prefix_space=lowerCamelCase_ , **lowerCamelCase_ , ) with open(lowerCamelCase_ , encoding='''utf-8''') as vocab_handle: UpperCamelCase = json.load(lowerCamelCase_) UpperCamelCase = {v: k for k, v in self.encoder.items()} UpperCamelCase = errors # how to handle errors in decoding UpperCamelCase = bytes_to_unicode() UpperCamelCase = {v: k for k, v in self.byte_encoder.items()} with open(lowerCamelCase_ , encoding='''utf-8''') as merges_handle: UpperCamelCase = merges_handle.read().split('''\n''')[1:-1] UpperCamelCase = [tuple(merge.split()) for merge in bpe_merges] UpperCamelCase = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_)))) UpperCamelCase = {} UpperCamelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCamelCase = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''') @property def UpperCAmelCase__ ( self) -> str: return len(self.encoder) def UpperCAmelCase__ ( self) -> Optional[Any]: return dict(self.encoder , **self.added_tokens_encoder) def UpperCAmelCase__ ( self , lowerCamelCase_) -> str: if token in self.cache: return self.cache[token] UpperCamelCase = tuple(lowerCamelCase_) UpperCamelCase = get_pairs(lowerCamelCase_) if not pairs: return token while True: UpperCamelCase = min(lowerCamelCase_ , key=lambda lowerCamelCase_: self.bpe_ranks.get(lowerCamelCase_ , float('''inf'''))) if bigram not in self.bpe_ranks: break UpperCamelCase , UpperCamelCase = bigram UpperCamelCase = [] UpperCamelCase = 0 while i < len(lowerCamelCase_): try: UpperCamelCase = word.index(lowerCamelCase_ , lowerCamelCase_) except ValueError: new_word.extend(word[i:]) break else: new_word.extend(word[i:j]) UpperCamelCase = j if word[i] == first and i < len(lowerCamelCase_) - 1 and word[i + 1] == second: new_word.append(first + second) i += 2 else: new_word.append(word[i]) i += 1 UpperCamelCase = tuple(lowerCamelCase_) UpperCamelCase = new_word if len(lowerCamelCase_) == 1: break else: UpperCamelCase = get_pairs(lowerCamelCase_) UpperCamelCase = ''' '''.join(lowerCamelCase_) UpperCamelCase = word return word def UpperCAmelCase__ ( self , lowerCamelCase_) -> Dict: UpperCamelCase = [] for token in re.findall(self.pat , lowerCamelCase_): UpperCamelCase = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''')) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase_).split(''' ''')) return bpe_tokens def UpperCAmelCase__ ( self , lowerCamelCase_) -> Union[str, Any]: return self.encoder.get(lowerCamelCase_ , self.encoder.get(self.unk_token)) def UpperCAmelCase__ ( self , lowerCamelCase_) -> List[Any]: return self.decoder.get(lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_) -> Any: UpperCamelCase = ''''''.join(lowerCamelCase_) UpperCamelCase = bytearray([self.byte_decoder[c] for c in text]).decode('''utf-8''' , errors=self.errors) return text def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None) -> Tuple[str]: if not os.path.isdir(lowerCamelCase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return UpperCamelCase = os.path.join( lowerCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) UpperCamelCase = os.path.join( lowerCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']) with open(lowerCamelCase_ , '''w''' , encoding='''utf-8''') as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCamelCase_ , ensure_ascii=lowerCamelCase_) + '''\n''') UpperCamelCase = 0 with open(lowerCamelCase_ , '''w''' , encoding='''utf-8''') as writer: writer.write('''#version: 0.2\n''') for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda lowerCamelCase_: kv[1]): if index != token_index: logger.warning( F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ''' Please check that the tokenizer is not corrupted!''') UpperCamelCase = token_index writer.write(''' '''.join(lowerCamelCase_) + '''\n''') index += 1 return vocab_file, merge_file def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None) -> List[int]: 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 UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None , lowerCamelCase_ = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_)) + [1] return [1] + ([0] * len(lowerCamelCase_)) + [1, 1] + ([0] * len(lowerCamelCase_)) + [1] def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None) -> List[int]: 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] def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_=False , **lowerCamelCase_) -> Dict: UpperCamelCase = kwargs.pop('''add_prefix_space''' , self.add_prefix_space) if (is_split_into_words or add_prefix_space) and (len(lowerCamelCase_) > 0 and not text[0].isspace()): UpperCamelCase = ''' ''' + text return (text, kwargs)
34
'''simple docstring''' import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a = logging.get_logger(__name__) a = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"} a = { "vocab_file": { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt", }, "emoji_file": { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json", }, } a = { "abeja/gpt-neox-japanese-2.7b": 2048, } def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Any: '''simple docstring''' with open(__UpperCAmelCase , """r""" , encoding="""utf-8""" ) as f: __SCREAMING_SNAKE_CASE = json.loads(f.read() ) __SCREAMING_SNAKE_CASE = collections.OrderedDict() __SCREAMING_SNAKE_CASE = collections.OrderedDict() __SCREAMING_SNAKE_CASE = collections.OrderedDict() with open(__UpperCAmelCase , """r""" , encoding="""utf-8""" ) as f: __SCREAMING_SNAKE_CASE = f.readlines() __SCREAMING_SNAKE_CASE = [[t.rstrip("""\n""" )] if (t == """,""" or """,""" not in t) else t.rstrip("""\n""" ).split(""",""" ) for t in token] for idx, b in enumerate(__UpperCAmelCase ): __SCREAMING_SNAKE_CASE = b __SCREAMING_SNAKE_CASE = idx for wd in b: __SCREAMING_SNAKE_CASE = idx return vocab, raw_vocab, ids_to_tokens, emoji class __a ( _snake_case ): __UpperCamelCase : Tuple = VOCAB_FILES_NAMES __UpperCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self : Dict ,lowerCamelCase : Union[str, Any] ,lowerCamelCase : int ,lowerCamelCase : str="<|endoftext|>" ,lowerCamelCase : List[Any]="<|endoftext|>" ,lowerCamelCase : str="<|startoftext|>" ,lowerCamelCase : Dict="<|endoftext|>" ,lowerCamelCase : int=False ,**lowerCamelCase : str ,): '''simple docstring''' super().__init__( unk_token=lowerCamelCase ,pad_token=lowerCamelCase ,bos_token=lowerCamelCase ,eos_token=lowerCamelCase ,do_clean_text=lowerCamelCase ,**lowerCamelCase ,) if not os.path.isfile(lowerCamelCase ): raise ValueError( f"""Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained""" """ model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`""" ) if not os.path.isfile(lowerCamelCase ): raise ValueError( f"""Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google""" """ pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`""" ) __SCREAMING_SNAKE_CASE = do_clean_text __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = load_vocab_and_emoji(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = SubWordJapaneseTokenizer( vocab=self.vocab ,ids_to_tokens=self.ids_to_tokens ,emoji=self.emoji ) @property def UpperCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' return len(self.raw_vocab ) def UpperCAmelCase__ ( self : List[str] ): '''simple docstring''' return dict(self.raw_vocab ,**self.added_tokens_encoder ) def UpperCAmelCase__ ( self : Dict ,lowerCamelCase : str ): '''simple docstring''' return self.subword_tokenizer.tokenize(lowerCamelCase ,clean=self.do_clean_text ) def UpperCAmelCase__ ( self : Union[str, Any] ,lowerCamelCase : Union[str, Any] ): '''simple docstring''' return self.vocab.get(lowerCamelCase ,self.vocab.get(self.unk_token ) ) def UpperCAmelCase__ ( self : List[Any] ,lowerCamelCase : Optional[Any] ): '''simple docstring''' return self.subword_tokenizer.convert_id_to_token(lowerCamelCase ) def UpperCAmelCase__ ( self : List[str] ,lowerCamelCase : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE = """""".join(lowerCamelCase ).strip() return out_string def UpperCAmelCase__ ( self : List[str] ,lowerCamelCase : "Conversation" ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase ,add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] return input_ids def UpperCAmelCase__ ( self : Dict ,lowerCamelCase : str ,lowerCamelCase : Optional[str] = None ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 if os.path.isdir(lowerCamelCase ): __SCREAMING_SNAKE_CASE = os.path.join( lowerCamelCase ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join( lowerCamelCase ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""emoji_file"""] ) else: __SCREAMING_SNAKE_CASE = ( (filename_prefix + """-""" if filename_prefix else """""") + save_directory + VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = ( (filename_prefix + """-""" if filename_prefix else """""") + save_directory + VOCAB_FILES_NAMES["""emoji_file"""] ) with open(lowerCamelCase ,"""w""" ,encoding="""utf-8""" ) as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( f"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" """ Please check that the vocabulary is not corrupted!""" ) __SCREAMING_SNAKE_CASE = token_index writer.write(""",""".join(lowerCamelCase ) + """\n""" ) index += 1 with open(lowerCamelCase ,"""w""" ,encoding="""utf-8""" ) as writer: json.dump(self.emoji ,lowerCamelCase ) return vocab_file, emoji_file class __a ( _snake_case ): def __init__( self : Tuple ,lowerCamelCase : List[str] ,lowerCamelCase : Union[str, Any] ,lowerCamelCase : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = vocab # same as swe __SCREAMING_SNAKE_CASE = ids_to_tokens # same as bpe __SCREAMING_SNAKE_CASE = emoji __SCREAMING_SNAKE_CASE = np.max([len(lowerCamelCase ) for w in self.vocab.keys()] ) __SCREAMING_SNAKE_CASE = re.compile(r"""(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)""" ) __SCREAMING_SNAKE_CASE = re.compile(r"""[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*""" ) __SCREAMING_SNAKE_CASE = re.compile(r"""[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}""" ) __SCREAMING_SNAKE_CASE = re.compile( r"""([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*""" ) __SCREAMING_SNAKE_CASE = re.compile( r"""(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*""" ) __SCREAMING_SNAKE_CASE = re.compile( r"""((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*""" ) __SCREAMING_SNAKE_CASE = """─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿""" __SCREAMING_SNAKE_CASE = """▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟""" __SCREAMING_SNAKE_CASE = str.maketrans({k: """<BLOCK>""" for k in keisen + blocks} ) def __len__( self : List[str] ): '''simple docstring''' return len(self.ids_to_tokens ) def UpperCAmelCase__ ( self : Optional[int] ,lowerCamelCase : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.content_repattera.sub("""<URL>""" ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = self.content_repattera.sub("""<EMAIL>""" ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = self.content_repattera.sub("""<TEL>""" ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = self.content_repattera.sub("""<DATE>""" ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = self.content_repattera.sub("""<DATE>""" ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = self.content_repattera.sub("""<PRICE>""" ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: __SCREAMING_SNAKE_CASE = content.replace("""<BLOCK><BLOCK>""" ,"""<BLOCK>""" ) return content def UpperCAmelCase__ ( self : Dict ,lowerCamelCase : Optional[Any] ,lowerCamelCase : List[str]=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = text.replace(""" """ ,"""<SP>""" ) __SCREAMING_SNAKE_CASE = text.replace(""" """ ,"""<SP>""" ) __SCREAMING_SNAKE_CASE = text.replace("""\r\n""" ,"""<BR>""" ) __SCREAMING_SNAKE_CASE = text.replace("""\n""" ,"""<BR>""" ) __SCREAMING_SNAKE_CASE = text.replace("""\r""" ,"""<BR>""" ) __SCREAMING_SNAKE_CASE = text.replace("""\t""" ,"""<TAB>""" ) __SCREAMING_SNAKE_CASE = text.replace("""—""" ,"""ー""" ) __SCREAMING_SNAKE_CASE = text.replace("""−""" ,"""ー""" ) for k, v in self.emoji["emoji"].items(): if k in text: __SCREAMING_SNAKE_CASE = text.replace(lowerCamelCase ,lowerCamelCase ) if clean: __SCREAMING_SNAKE_CASE = self.clean_text(lowerCamelCase ) def check_simbol(lowerCamelCase : List[str] ): __SCREAMING_SNAKE_CASE = x.encode() if len(lowerCamelCase ) == 1 and len(lowerCamelCase ) == 2: __SCREAMING_SNAKE_CASE = (int(e[0] ) << 8) + int(e[1] ) if ( (c >= 0xC_2A1 and c <= 0xC_2BF) or (c >= 0xC_780 and c <= 0xC_783) or (c >= 0xC_AB9 and c <= 0xC_BBF) or (c >= 0xC_C80 and c <= 0xC_DA2) ): return True return False def checkuae(lowerCamelCase : Union[str, Any] ): __SCREAMING_SNAKE_CASE = x.encode() if len(lowerCamelCase ) == 1 and len(lowerCamelCase ) == 3: __SCREAMING_SNAKE_CASE = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0xE28_080 and c <= 0xE2B_07F: return True return False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [] while pos < len(lowerCamelCase ): __SCREAMING_SNAKE_CASE = min(len(lowerCamelCase ) ,pos + self.maxlen + 1 ) if text[pos] == """<""" else pos + 3 __SCREAMING_SNAKE_CASE = [] # (token_id, token, pos) for e in range(lowerCamelCase ,lowerCamelCase ,-1 ): __SCREAMING_SNAKE_CASE = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(lowerCamelCase ) > 2: __SCREAMING_SNAKE_CASE = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(lowerCamelCase ) > 0: # the smallest token_id is adopted __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sorted(lowerCamelCase ,key=lambda lowerCamelCase : x[0] )[0] result.append(lowerCamelCase ) __SCREAMING_SNAKE_CASE = e else: __SCREAMING_SNAKE_CASE = pos + 1 __SCREAMING_SNAKE_CASE = text[pos:end] if check_simbol(lowerCamelCase ): result.append("""<KIGOU>""" ) elif checkuae(lowerCamelCase ): result.append("""<U2000U2BFF>""" ) else: for i in wd.encode("""utf-8""" ): result.append("""<|byte%d|>""" % i ) __SCREAMING_SNAKE_CASE = end return result def UpperCAmelCase__ ( self : Optional[Any] ,lowerCamelCase : Dict ,lowerCamelCase : Optional[Any]="\n" ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(lowerCamelCase ) > 0: words.append(bytearray(lowerCamelCase ).decode("""utf-8""" ,errors="""replace""" ) ) __SCREAMING_SNAKE_CASE = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji["""emoji_inv"""][word] ) elif word == "<SP>": words.append(""" """ ) elif word == "<BR>": words.append(lowerCamelCase ) elif word == "<TAB>": words.append("""\t""" ) elif word == "<BLOCK>": words.append("""▀""" ) elif word == "<KIGOU>": words.append("""ǀ""" ) elif word == "<U2000U2BFF>": words.append("""‖""" ) else: words.append(lowerCamelCase ) if len(lowerCamelCase ) > 0: words.append(bytearray(lowerCamelCase ).decode("""utf-8""" ,errors="""replace""" ) ) __SCREAMING_SNAKE_CASE = """""".join(lowerCamelCase ) return text
109
0
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class a ( __lowerCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase :int = VideoToVideoSDPipeline lowerCamelCase :Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'''video'''} ) - {'''image''', '''width''', '''height'''} lowerCamelCase :Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''video'''} ) - {'''image'''} lowerCamelCase :Union[str, Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} lowerCamelCase :int = False # No `output_type`. lowerCamelCase :Union[str, Any] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def UpperCAmelCase ( self ) -> Optional[Any]: torch.manual_seed(0 ) _A = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) _A = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowerCAmelCase_ , set_alpha_to_one=lowerCAmelCase_ , ) torch.manual_seed(0 ) _A = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) _A = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="""gelu""" , projection_dim=5_12 , ) _A = CLIPTextModel(lowerCAmelCase_ ) _A = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _A = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Optional[Any]: # 3 frames _A = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(lowerCAmelCase_ ) ).to(lowerCAmelCase_ ) if str(lowerCAmelCase_ ).startswith("""mps""" ): _A = torch.manual_seed(lowerCAmelCase_ ) else: _A = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _A = { """prompt""": """A painting of a squirrel eating a burger""", """video""": video, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def UpperCAmelCase ( self ) -> Dict: _A = """cpu""" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = VideoToVideoSDPipeline(**lowerCAmelCase_ ) _A = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A = self.get_dummy_inputs(lowerCAmelCase_ ) _A = """np""" _A = sd_pipe(**lowerCAmelCase_ ).frames _A = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) _A = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCAmelCase ( self ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCAmelCase_ , expected_max_diff=5E-3 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCAmelCase ( self ) -> Tuple: pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCAmelCase ( self ) -> Optional[Any]: pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> int: return super().test_progress_bar() @slow @skip_mps class a ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: _A = VideoToVideoSDPipeline.from_pretrained("""cerspense/zeroscope_v2_XL""" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames _A = torch.Generator(device="""cpu""" ).manual_seed(0 ) _A = torch.randn((1, 10, 3, 10_24, 5_76) , generator=lowerCAmelCase_ ) _A = video.to("""cuda""" ) _A = """Spiderman is surfing""" _A = pipe(lowerCAmelCase_ , video=lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=3 , output_type="""pt""" ).frames _A = np.array([-1.045_8984, -1.127_9297, -0.966_3086, -0.9150_3906, -0.7509_7656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
83
import numpy as np import qiskit def snake_case ( snake_case__ :int = 8 , snake_case__ :int | None = None) -> str: _A = np.random.default_rng(seed=snake_case__) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _A = 6 * key_len # Measurement basis for Alice's qubits. _A = rng.integers(2 , size=snake_case__) # The set of states Alice will prepare. _A = rng.integers(2 , size=snake_case__) # Measurement basis for Bob's qubits. _A = rng.integers(2 , size=snake_case__) # Quantum Circuit to simulate BB84 _A = qiskit.QuantumCircuit(snake_case__ , name="""BB84""") # Alice prepares her qubits according to rules above. for index, _ in enumerate(snake_case__): if alice_state[index] == 1: bbaa_circ.x(snake_case__) if alice_basis[index] == 1: bbaa_circ.h(snake_case__) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(snake_case__): if bob_basis[index] == 1: bbaa_circ.h(snake_case__) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _A = qiskit.Aer.get_backend("""aer_simulator""") # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _A = qiskit.execute(snake_case__ , snake_case__ , shots=1 , seed_simulator=snake_case__) # Returns the result of measurement. _A = job.result().get_counts(snake_case__).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _A = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( snake_case__ , snake_case__ , snake_case__) if alice_basis_bit == bob_basis_bit ]) # Get final key. Pad with 0 if too short, otherwise truncate. _A = gen_key[:key_len] if len(snake_case__) >= key_len else gen_key.ljust(snake_case__ , """0""") return key if __name__ == "__main__": print(F'''The generated key is : {bbaa(8, seed=0)}''') from doctest import testmod testmod()
83
1
def lowerCAmelCase__ ( a__ = 50 ) ->str: '''simple docstring''' _UpperCamelCase = [1] * (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 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F"{solution() = }")
547
from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class _SCREAMING_SNAKE_CASE : __SCREAMING_SNAKE_CASE = BlenderbotConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=False , A_=99 , A_=32 , A_=2 , A_=4 , A_=37 , A_=0.1 , A_=0.1 , A_=20 , A_=2 , A_=1 , A_=0 , ): _UpperCAmelCase : List[str] = parent _UpperCAmelCase : Union[str, Any] = batch_size _UpperCAmelCase : Optional[Any] = seq_length _UpperCAmelCase : List[Any] = is_training _UpperCAmelCase : Union[str, Any] = use_labels _UpperCAmelCase : Tuple = vocab_size _UpperCAmelCase : Optional[int] = hidden_size _UpperCAmelCase : int = num_hidden_layers _UpperCAmelCase : List[Any] = num_attention_heads _UpperCAmelCase : List[Any] = intermediate_size _UpperCAmelCase : Union[str, Any] = hidden_dropout_prob _UpperCAmelCase : str = attention_probs_dropout_prob _UpperCAmelCase : Optional[int] = max_position_embeddings _UpperCAmelCase : Optional[Any] = eos_token_id _UpperCAmelCase : Optional[Any] = pad_token_id _UpperCAmelCase : Tuple = bos_token_id def __snake_case( self ): _UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCAmelCase : Tuple = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCAmelCase : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase : List[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 , ) _UpperCAmelCase : Dict = prepare_blenderbot_inputs_dict(A_ , A_ , A_ ) return config, inputs_dict def __snake_case( self , A_ , A_ ): _UpperCAmelCase : Union[str, Any] = TFBlenderbotModel(config=A_ ).get_decoder() _UpperCAmelCase : List[Any] = inputs_dict["""input_ids"""] _UpperCAmelCase : Any = input_ids[:1, :] _UpperCAmelCase : List[str] = inputs_dict["""attention_mask"""][:1, :] _UpperCAmelCase : Tuple = inputs_dict["""head_mask"""] _UpperCAmelCase : Union[str, Any] = 1 # first forward pass _UpperCAmelCase : List[str] = model(A_ , attention_mask=A_ , head_mask=A_ , use_cache=A_ ) _UpperCAmelCase,_UpperCAmelCase : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCAmelCase : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCAmelCase : List[str] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCAmelCase : Dict = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCAmelCase : Optional[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCAmelCase : Tuple = model(A_ , attention_mask=A_ )[0] _UpperCAmelCase : int = model(A_ , attention_mask=A_ , past_key_values=A_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCAmelCase : Tuple = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCAmelCase : str = output_from_no_past[:, -3:, random_slice_idx] _UpperCAmelCase : str = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A_ , A_ , rtol=1e-3 ) def a__ ( snake_case__ : Optional[Any] , snake_case__ : str , snake_case__ : Dict , snake_case__ : str=None , snake_case__ : Optional[int]=None , snake_case__ : str=None , snake_case__ : List[str]=None , snake_case__ : List[str]=None , ): if attention_mask is None: _UpperCAmelCase : List[Any] = tf.cast(tf.math.not_equal(snake_case__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _UpperCAmelCase : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _UpperCAmelCase : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCAmelCase : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _UpperCAmelCase : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _SCREAMING_SNAKE_CASE ( A , A , unittest.TestCase ): __SCREAMING_SNAKE_CASE = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () __SCREAMING_SNAKE_CASE = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () __SCREAMING_SNAKE_CASE = ( { '''conversational''': TFBlenderbotForConditionalGeneration, '''feature-extraction''': TFBlenderbotModel, '''summarization''': TFBlenderbotForConditionalGeneration, '''text2text-generation''': TFBlenderbotForConditionalGeneration, '''translation''': TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __snake_case( self ): _UpperCAmelCase : Union[str, Any] = TFBlenderbotModelTester(self ) _UpperCAmelCase : Any = ConfigTester(self , config_class=A_ ) def __snake_case( self ): self.config_tester.run_common_tests() def __snake_case( self ): _UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A_ ) @require_tokenizers @require_tf class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): __SCREAMING_SNAKE_CASE = ['''My friends are cool but they eat too many carbs.'''] __SCREAMING_SNAKE_CASE = '''facebook/blenderbot-400M-distill''' @cached_property def __snake_case( self ): return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def __snake_case( self ): _UpperCAmelCase : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def __snake_case( self ): _UpperCAmelCase : Any = self.tokenizer(self.src_text , return_tensors="""tf""" ) _UpperCAmelCase : List[Any] = self.model.generate( model_inputs.input_ids , ) _UpperCAmelCase : List[str] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A_ )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
643
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_convbert''': ['''CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConvBertConfig''', '''ConvBertOnnxConfig'''], '''tokenization_convbert''': ['''ConvBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''ConvBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConvBertForMaskedLM''', '''ConvBertForMultipleChoice''', '''ConvBertForQuestionAnswering''', '''ConvBertForSequenceClassification''', '''ConvBertForTokenClassification''', '''ConvBertLayer''', '''ConvBertModel''', '''ConvBertPreTrainedModel''', '''load_tf_weights_in_convbert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFConvBertForMaskedLM''', '''TFConvBertForMultipleChoice''', '''TFConvBertForQuestionAnswering''', '''TFConvBertForSequenceClassification''', '''TFConvBertForTokenClassification''', '''TFConvBertLayer''', '''TFConvBertModel''', '''TFConvBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
544
"""simple docstring""" import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class _lowerCamelCase : def __init__(self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=64 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> Optional[int]: UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_input_mask UpperCamelCase = use_token_type_ids UpperCamelCase = use_labels UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range UpperCamelCase = num_labels UpperCamelCase = num_choices UpperCamelCase = scope UpperCamelCase = vocab_size - 1 def snake_case_ (self ) -> List[Any]: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = None if self.use_input_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase = self.get_config() return config, input_ids, input_mask, token_labels def snake_case_ (self ) -> int: return GPTNeoXConfig( 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 , pad_token_id=self.pad_token_id , ) def snake_case_ (self ) -> int: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase = True return config, input_ids, input_mask, token_labels def snake_case_ (self , __a , __a , __a ) -> Optional[int]: UpperCamelCase = GPTNeoXModel(config=__a ) model.to(__a ) model.eval() UpperCamelCase = model(__a , attention_mask=__a ) UpperCamelCase = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case_ (self , __a , __a , __a ) -> Optional[int]: UpperCamelCase = True UpperCamelCase = GPTNeoXModel(__a ) model.to(__a ) model.eval() UpperCamelCase = model(__a , attention_mask=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case_ (self , __a , __a , __a , __a ) -> List[Any]: UpperCamelCase = GPTNeoXForCausalLM(config=__a ) model.to(__a ) model.eval() UpperCamelCase = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case_ (self , __a , __a , __a , __a ) -> Optional[int]: UpperCamelCase = self.num_labels UpperCamelCase = GPTNeoXForQuestionAnswering(__a ) model.to(__a ) model.eval() UpperCamelCase = model(__a , attention_mask=__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 snake_case_ (self , __a , __a , __a , __a ) -> Optional[int]: UpperCamelCase = self.num_labels UpperCamelCase = GPTNeoXForSequenceClassification(__a ) model.to(__a ) model.eval() UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case_ (self , __a , __a , __a , __a ) -> str: UpperCamelCase = self.num_labels UpperCamelCase = GPTNeoXForTokenClassification(__a ) model.to(__a ) model.eval() UpperCamelCase = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def snake_case_ (self , __a , __a , __a ) -> Any: UpperCamelCase = True UpperCamelCase = GPTNeoXForCausalLM(config=__a ) model.to(__a ) model.eval() # first forward pass UpperCamelCase = model(__a , attention_mask=__a , use_cache=__a ) UpperCamelCase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and UpperCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase = torch.cat([input_mask, next_mask] , dim=-1 ) UpperCamelCase = model(__a , attention_mask=__a , output_hidden_states=__a ) UpperCamelCase = output_from_no_past["hidden_states"][0] UpperCamelCase = model( __a , attention_mask=__a , past_key_values=__a , output_hidden_states=__a , )["hidden_states"][0] # select random slice UpperCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase = 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 snake_case_ (self ) -> str: UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _lowerCamelCase ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): UpperCAmelCase_ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) UpperCAmelCase_ = (GPTNeoXForCausalLM,) if is_torch_available() else () UpperCAmelCase_ = ( { "feature-extraction": GPTNeoXModel, "question-answering": GPTNeoXForQuestionAnswering, "text-classification": GPTNeoXForSequenceClassification, "text-generation": GPTNeoXForCausalLM, "token-classification": GPTNeoXForTokenClassification, "zero-shot": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def snake_case_ (self ) -> str: UpperCamelCase = GPTNeoXModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=64 , num_attention_heads=8 ) def snake_case_ (self ) -> int: self.config_tester.run_common_tests() def snake_case_ (self ) -> Optional[int]: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a , __a , __a ) def snake_case_ (self ) -> str: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(__a , __a , __a ) def snake_case_ (self ) -> Optional[Any]: # This regression test was failing with PyTorch < 1.3 UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() UpperCamelCase = None self.model_tester.create_and_check_model_as_decoder(__a , __a , __a ) def snake_case_ (self ) -> Union[str, Any]: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(__a , __a , __a ) def snake_case_ (self ) -> Any: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*__a ) def snake_case_ (self ) -> Union[str, Any]: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__a ) def snake_case_ (self ) -> Optional[int]: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__a ) def snake_case_ (self ) -> Optional[int]: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__a ) @unittest.skip(reason="Feed forward chunking is not implemented" ) def snake_case_ (self ) -> Any: pass @parameterized.expand([("linear",), ("dynamic",)] ) def snake_case_ (self , __a ) -> Dict: UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = ids_tensor([1, 10] , config.vocab_size ) UpperCamelCase = 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 UpperCamelCase = GPTNeoXModel(__a ) original_model.to(__a ) original_model.eval() UpperCamelCase = original_model(__a ).last_hidden_state UpperCamelCase = original_model(__a ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights UpperCamelCase = {"type": scaling_type, "factor": 10.0} UpperCamelCase = GPTNeoXModel(__a ) scaled_model.to(__a ) scaled_model.eval() UpperCamelCase = scaled_model(__a ).last_hidden_state UpperCamelCase = 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 ) ) @require_torch class _lowerCamelCase ( unittest.TestCase ): @slow def snake_case_ (self ) -> Optional[int]: UpperCamelCase = AutoTokenizer.from_pretrained("EleutherAI/pythia-410m-deduped" ) for checkpointing in [True, False]: UpperCamelCase = GPTNeoXForCausalLM.from_pretrained("EleutherAI/pythia-410m-deduped" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(__a ) UpperCamelCase = tokenizer("My favorite food is" , return_tensors="pt" ).to(__a ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 UpperCamelCase = "My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure" UpperCamelCase = model.generate(**__a , do_sample=__a , max_new_tokens=20 ) UpperCamelCase = tokenizer.batch_decode(__a )[0] self.assertEqual(__a , __a )
544
1
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def lowercase__ ( __UpperCamelCase : int ): '''simple docstring''' return EnvironmentCommand() def lowercase__ ( __UpperCamelCase : Tuple ): '''simple docstring''' return EnvironmentCommand(args.accelerate_config_file ) class lowerCamelCase__( snake_case_ ): @staticmethod def __magic_name__ ( __UpperCAmelCase ): """simple docstring""" __lowercase = parser.add_parser("""env""" ) download_parser.set_defaults(func=__UpperCAmelCase ) download_parser.add_argument( """--accelerate-config_file""" , default=__UpperCAmelCase , help="""The accelerate config file to use for the default values in the launching script.""" , ) download_parser.set_defaults(func=__UpperCAmelCase ) def __init__( self , __UpperCAmelCase , *__UpperCAmelCase ): """simple docstring""" __lowercase = accelerate_config_file def __magic_name__ ( self ): """simple docstring""" __lowercase = """not installed""" if is_safetensors_available(): import safetensors __lowercase = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors __lowercase = F'''{safetensors.__version__} but is ignored because of PyTorch version too old.''' __lowercase = """not installed""" __lowercase = __lowercase = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file __lowercase = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__UpperCAmelCase ): __lowercase = load_config_from_file(self._accelerate_config_file ).to_dict() __lowercase = ( """\n""".join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else F'''\t{accelerate_config}''' ) __lowercase = """not installed""" __lowercase = """NA""" if is_torch_available(): import torch __lowercase = torch.__version__ __lowercase = torch.cuda.is_available() __lowercase = """not installed""" __lowercase = """NA""" if is_tf_available(): import tensorflow as tf __lowercase = tf.__version__ try: # deprecated in v2.1 __lowercase = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool __lowercase = bool(tf.config.list_physical_devices("""GPU""" ) ) __lowercase = """not installed""" __lowercase = """not installed""" __lowercase = """not installed""" __lowercase = """NA""" if is_flax_available(): import flax import jax import jaxlib __lowercase = flax.__version__ __lowercase = jax.__version__ __lowercase = jaxlib.__version__ __lowercase = jax.lib.xla_bridge.get_backend().platform __lowercase = { """`transformers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Huggingface_hub version""": huggingface_hub.__version__, """Safetensors version""": F'''{safetensors_version}''', """Accelerate version""": F'''{accelerate_version}''', """Accelerate config""": F'''{accelerate_config_str}''', """PyTorch version (GPU?)""": F'''{pt_version} ({pt_cuda_available})''', """Tensorflow version (GPU?)""": F'''{tf_version} ({tf_cuda_available})''', """Flax version (CPU?/GPU?/TPU?)""": F'''{flax_version} ({jax_backend})''', """Jax version""": F'''{jax_version}''', """JaxLib version""": F'''{jaxlib_version}''', """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(__UpperCAmelCase ) ) return info @staticmethod def __magic_name__ ( __UpperCAmelCase ): """simple docstring""" return "\n".join([F'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
566
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : int = logging.get_logger(__name__) snake_case : Optional[Any] = { 'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json', } class lowerCamelCase__( snake_case_ ): UpperCamelCase : str = "git_vision_model" def __init__( self , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3 , __UpperCAmelCase=2_2_4 , __UpperCAmelCase=1_6 , __UpperCAmelCase="quick_gelu" , __UpperCAmelCase=1E-5 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.02 , **__UpperCAmelCase , ): """simple docstring""" super().__init__(**__UpperCAmelCase ) __lowercase = hidden_size __lowercase = intermediate_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = num_channels __lowercase = patch_size __lowercase = image_size __lowercase = initializer_range __lowercase = attention_dropout __lowercase = layer_norm_eps __lowercase = hidden_act @classmethod def __magic_name__ ( cls , __UpperCAmelCase , **__UpperCAmelCase ): """simple docstring""" cls._set_token_in_kwargs(__UpperCAmelCase ) __lowercase , __lowercase = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": __lowercase = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class lowerCamelCase__( snake_case_ ): UpperCamelCase : Any = "git" def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=3_0_5_2_2 , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=6 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=1_0_2_4 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=0 , __UpperCAmelCase="absolute" , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=1_0_1 , __UpperCAmelCase=1_0_2 , __UpperCAmelCase=None , **__UpperCAmelCase , ): """simple docstring""" super().__init__(bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , pad_token_id=__UpperCAmelCase , **__UpperCAmelCase ) if vision_config is None: __lowercase = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) __lowercase = GitVisionConfig(**__UpperCAmelCase ) __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = hidden_act __lowercase = intermediate_size __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = position_embedding_type __lowercase = use_cache __lowercase = tie_word_embeddings __lowercase = num_image_with_embedding __lowercase = bos_token_id __lowercase = eos_token_id def __magic_name__ ( self ): """simple docstring""" __lowercase = copy.deepcopy(self.__dict__ ) __lowercase = self.vision_config.to_dict() __lowercase = self.__class__.model_type return output
566
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ : List[str] = { '''configuration_albert''': ['''ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AlbertConfig''', '''AlbertOnnxConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : Union[str, Any] = ['''AlbertTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : str = ['''AlbertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : List[Any] = [ '''ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AlbertForMaskedLM''', '''AlbertForMultipleChoice''', '''AlbertForPreTraining''', '''AlbertForQuestionAnswering''', '''AlbertForSequenceClassification''', '''AlbertForTokenClassification''', '''AlbertModel''', '''AlbertPreTrainedModel''', '''load_tf_weights_in_albert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : Any = [ '''TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFAlbertForMaskedLM''', '''TFAlbertForMultipleChoice''', '''TFAlbertForPreTraining''', '''TFAlbertForQuestionAnswering''', '''TFAlbertForSequenceClassification''', '''TFAlbertForTokenClassification''', '''TFAlbertMainLayer''', '''TFAlbertModel''', '''TFAlbertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : Union[str, Any] = [ '''FlaxAlbertForMaskedLM''', '''FlaxAlbertForMultipleChoice''', '''FlaxAlbertForPreTraining''', '''FlaxAlbertForQuestionAnswering''', '''FlaxAlbertForSequenceClassification''', '''FlaxAlbertForTokenClassification''', '''FlaxAlbertModel''', '''FlaxAlbertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys lowercase_ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
716
"""simple docstring""" 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 TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : str = TFCamembertModel.from_pretrained("jplu/tf-camembert-base" ) _SCREAMING_SNAKE_CASE : str = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" _SCREAMING_SNAKE_CASE : str = model(snake_case__ )["last_hidden_state"] _SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , snake_case__ ) # compare the actual values for a slice. _SCREAMING_SNAKE_CASE : int = tf.convert_to_tensor( [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
295
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase: str = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase: Any = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase: int = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase: Any = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase: Optional[int] = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys _lowercase: Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
192
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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class lowerCamelCase__ ( unittest.TestCase ): def __init__( self : List[str] , lowercase__ : Any , lowercase__ : List[Any]=7 , lowercase__ : List[str]=3 , lowercase__ : str=18 , lowercase__ : List[Any]=30 , lowercase__ : Optional[int]=4_00 , lowercase__ : Dict=True , lowercase__ : List[str]=None , lowercase__ : int=True , lowercase__ : Tuple=None , lowercase__ : int=True , lowercase__ : Tuple=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , lowercase__ : Optional[int]=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , lowercase__ : Any=True , ): _lowerCAmelCase = size if size is not None else {'height': 2_24, 'width': 2_24} _lowerCAmelCase = crop_size if crop_size is not None else {'height': 18, 'width': 18} _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = num_channels _lowerCAmelCase = image_size _lowerCAmelCase = min_resolution _lowerCAmelCase = max_resolution _lowerCAmelCase = do_resize _lowerCAmelCase = size _lowerCAmelCase = do_center_crop _lowerCAmelCase = crop_size _lowerCAmelCase = do_normalize _lowerCAmelCase = image_mean _lowerCAmelCase = image_std _lowerCAmelCase = do_convert_rgb def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ ( self : List[str] , lowercase__ : Tuple=False , lowercase__ : List[Any]=False , lowercase__ : str=False ): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: _lowerCAmelCase = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 2_55 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: _lowerCAmelCase = [] for i in range(self.batch_size ): _lowerCAmelCase , _lowerCAmelCase = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(2_55 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension _lowerCAmelCase = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: _lowerCAmelCase = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class lowerCamelCase__ ( UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ =ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self : Tuple ): _lowerCAmelCase = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Any ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self : Tuple ): _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , 'do_resize' ) ) self.assertTrue(hasattr(lowercase__ , 'size' ) ) self.assertTrue(hasattr(lowercase__ , 'do_center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'do_normalize' ) ) self.assertTrue(hasattr(lowercase__ , 'image_mean' ) ) self.assertTrue(hasattr(lowercase__ , 'image_std' ) ) self.assertTrue(hasattr(lowercase__ , 'do_convert_rgb' ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): _lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 2_24, 'width': 2_24} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) _lowerCAmelCase = 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 SCREAMING_SNAKE_CASE__ ( self : List[Any] ): pass def SCREAMING_SNAKE_CASE__ ( self : str ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input _lowerCAmelCase = 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 _lowerCAmelCase = image_processing(lowercase__ , 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 SCREAMING_SNAKE_CASE__ ( self : Any ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input _lowerCAmelCase = 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 _lowerCAmelCase = image_processing(lowercase__ , 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 SCREAMING_SNAKE_CASE__ ( self : int ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input _lowerCAmelCase = 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 _lowerCAmelCase = image_processing(lowercase__ , 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'], ) , ) @require_torch @require_vision class lowerCamelCase__ ( UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ =ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): _lowerCAmelCase = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) _lowerCAmelCase = 3 @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , 'do_resize' ) ) self.assertTrue(hasattr(lowercase__ , 'size' ) ) self.assertTrue(hasattr(lowercase__ , 'do_center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'center_crop' ) ) self.assertTrue(hasattr(lowercase__ , 'do_normalize' ) ) self.assertTrue(hasattr(lowercase__ , 'image_mean' ) ) self.assertTrue(hasattr(lowercase__ , 'image_std' ) ) self.assertTrue(hasattr(lowercase__ , 'do_convert_rgb' ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): pass def SCREAMING_SNAKE_CASE__ ( self : Dict ): # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input _lowerCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _lowerCAmelCase = image_processing(lowercase__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
192
1
'''simple docstring''' import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class lowercase_ : """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Tuple ,lowercase__ : Any ,lowercase__ : Optional[Any] ): return None class lowercase_ : """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Dict ,lowercase__ : List[Any] ,lowercase__ : int ,lowercase__ : Optional[Any] ): return None class lowercase_ (unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def SCREAMING_SNAKE_CASE ( self : str ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(lowercase__ ,'''tf''' ,1_2 ,**lowercase__ ) @require_torch @slow def SCREAMING_SNAKE_CASE ( self : int ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(lowercase__ ,'''pt''' ,1_2 ,**lowercase__ ) @require_torch @slow def SCREAMING_SNAKE_CASE ( self : Dict ): from transformers import BertModel __lowercase = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(lowercase__ ) ) vocab_file.flush() __lowercase = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: __lowercase = BertModel(BertConfig(vocab_size=len(lowercase__ ) ) ) model.save_pretrained(lowercase__ ) self._test_export(lowercase__ ,'''pt''' ,1_2 ,lowercase__ ) @require_tf @slow def SCREAMING_SNAKE_CASE ( self : Any ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: __lowercase = self._test_export(lowercase__ ,'''tf''' ,1_2 ,**lowercase__ ) __lowercase = quantize(Path(lowercase__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(lowercase__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def SCREAMING_SNAKE_CASE ( self : str ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: __lowercase = self._test_export(lowercase__ ,'''pt''' ,1_2 ,**lowercase__ ) __lowercase = quantize(lowercase__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(lowercase__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : List[str] ,lowercase__ : List[str] ,lowercase__ : Optional[int] ,lowercase__ : List[str]=None ,**lowercase__ : Union[str, Any] ): try: # Compute path with TemporaryDirectory() as tempdir: __lowercase = Path(lowercase__ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,**lowercase__ ) return path except Exception as e: self.fail(lowercase__ ) @require_torch @require_tokenizers @slow def SCREAMING_SNAKE_CASE ( self : Dict ): from transformers import BertModel __lowercase = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) __lowercase = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(lowercase__ ,lowercase__ ,'''pt''' ) @require_tf @require_tokenizers @slow def SCREAMING_SNAKE_CASE ( self : List[str] ): from transformers import TFBertModel __lowercase = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) __lowercase = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(lowercase__ ,lowercase__ ,'''tf''' ) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Dict ,lowercase__ : List[str] ,lowercase__ : Optional[int] ): __lowercase = FeatureExtractionPipeline(lowercase__ ,lowercase__ ) __lowercase = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] __lowercase , __lowercase , __lowercase , __lowercase = infer_shapes(lowercase__ ,lowercase__ ) # Assert all variables are present self.assertEqual(len(lowercase__ ) ,len(lowercase__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] ,lowercase__ ) self.assertSequenceEqual(variable_names[3:] ,lowercase__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] ,{0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] ,{0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] ,{0: '''batch'''} ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): __lowercase = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] __lowercase = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} __lowercase , __lowercase = ensure_valid_input(FuncContiguousArgs() ,lowercase__ ,lowercase__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(lowercase__ ) ,3 ) # Should have exactly the same input names self.assertEqual(set(lowercase__ ) ,set(lowercase__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(lowercase__ ,(tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) __lowercase , __lowercase = ensure_valid_input(FuncNonContiguousArgs() ,lowercase__ ,lowercase__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(lowercase__ ) ,1 ) self.assertEqual(len(lowercase__ ) ,1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] ,tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] ,'''input_ids''' ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) ,'''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' ,generated.as_posix() )
624
'''simple docstring''' def _A ( ): """simple docstring""" for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def _A ( A__ ): """simple docstring""" __lowercase = 1 __lowercase = 2 while i * i <= n: __lowercase = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(A__ ) > 500 ) if __name__ == "__main__": print(solution())
624
1
"""simple docstring""" from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def __lowerCamelCase ( __UpperCamelCase ) -> List[str]: """simple docstring""" if isinstance(__UpperCamelCase , collections.abc.Iterable ): return x return (x, x) @require_tf class __lowerCamelCase : '''simple docstring''' def lowerCamelCase ( self : Any , a_ : Optional[Any] , a_ : Union[str, Any] ): pass def lowerCamelCase ( self : int ): pass def lowerCamelCase ( self : Any ): pass def lowerCamelCase ( self : Optional[Any] , a_ : Union[str, Any] , a_ : List[str] , a_ : Any , a_ : str , a_ : Optional[int]=None , **a_ : int ): lowerCAmelCase_ : Union[str, Any] = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) lowerCAmelCase_ : List[str] = TFVisionTextDualEncoderModel(a_ ) lowerCAmelCase_ : int = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def lowerCamelCase ( self : str , a_ : List[Any] , a_ : Dict , a_ : Any , a_ : Union[str, Any] , a_ : Tuple=None , **a_ : Tuple ): lowerCAmelCase_ , lowerCAmelCase_ : List[str] = self.get_vision_text_model(a_ , a_ ) lowerCAmelCase_ : List[str] = TFVisionTextDualEncoderModel(vision_model=a_ , text_model=a_ ) lowerCAmelCase_ : int = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def lowerCamelCase ( self : Dict , a_ : Optional[Any] , a_ : Optional[Any] , a_ : Dict , a_ : Union[str, Any] , a_ : str=None , **a_ : Optional[int] ): lowerCAmelCase_ , lowerCAmelCase_ : str = self.get_vision_text_model(a_ , a_ ) lowerCAmelCase_ : List[Any] = {"vision_model": vision_model, "text_model": text_model} lowerCAmelCase_ : str = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) lowerCAmelCase_ : str = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def lowerCamelCase ( self : int , a_ : Tuple , a_ : Tuple , a_ : Tuple , a_ : Tuple , a_ : Optional[Any]=None , **a_ : List[str] ): lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = self.get_vision_text_model(a_ , a_ ) lowerCAmelCase_ : Optional[Any] = TFVisionTextDualEncoderModel(vision_model=a_ , text_model=a_ ) lowerCAmelCase_ : Any = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) lowerCAmelCase_ : Dict = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a_ ) lowerCAmelCase_ : Dict = TFVisionTextDualEncoderModel.from_pretrained(a_ ) lowerCAmelCase_ : Any = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) lowerCAmelCase_ : Optional[Any] = after_output[0].numpy() lowerCAmelCase_ : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-5 ) def lowerCamelCase ( self : List[Any] , a_ : str , a_ : str , a_ : Dict , a_ : Tuple , a_ : List[Any]=None , **a_ : List[str] ): lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = self.get_vision_text_model(a_ , a_ ) lowerCAmelCase_ : Optional[Any] = TFVisionTextDualEncoderModel(vision_model=a_ , text_model=a_ ) lowerCAmelCase_ : int = model( input_ids=a_ , pixel_values=a_ , attention_mask=a_ , output_attentions=a_ ) lowerCAmelCase_ : Any = output.vision_model_output.attentions self.assertEqual(len(a_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase_ : List[str] = to_atuple(vision_model.config.image_size ) lowerCAmelCase_ : int = to_atuple(vision_model.config.patch_size ) lowerCAmelCase_ : Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowerCAmelCase_ : Tuple = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowerCAmelCase_ : Optional[Any] = output.text_model_output.attentions self.assertEqual(len(a_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def lowerCamelCase ( self : List[Any] , a_ : np.ndarray , a_ : np.ndarray , a_ : float ): lowerCAmelCase_ : Optional[int] = np.abs((a - b) ).max() self.assertLessEqual(a_ , a_ , f'''Difference between torch and flax is {diff} (>= {tol}).''' ) def lowerCamelCase ( self : int ): lowerCAmelCase_ : Dict = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**a_ ) def lowerCamelCase ( self : Tuple ): lowerCAmelCase_ : Dict = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**a_ ) def lowerCamelCase ( self : Optional[int] ): lowerCAmelCase_ : List[str] = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**a_ ) def lowerCamelCase ( self : Dict ): lowerCAmelCase_ : Union[str, Any] = self.prepare_config_and_inputs() self.check_save_load(**a_ ) def lowerCamelCase ( self : Optional[Any] ): lowerCAmelCase_ : Any = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**a_ ) @slow def lowerCamelCase ( self : Any ): lowerCAmelCase_ , lowerCAmelCase_ : Dict = self.get_pretrained_model_and_inputs() lowerCAmelCase_ : Any = model_a(**a_ ) lowerCAmelCase_ : Dict = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(a_ ) lowerCAmelCase_ : Dict = TFVisionTextDualEncoderModel.from_pretrained(a_ ) lowerCAmelCase_ : List[str] = model_a(**a_ ) lowerCAmelCase_ : List[Any] = after_outputs[0].numpy() lowerCAmelCase_ : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-5 ) @require_tf class __lowerCamelCase ( A__ , unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : Dict ): lowerCAmelCase_ : List[Any] = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) lowerCAmelCase_ : Tuple = 13 lowerCAmelCase_ : int = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowerCAmelCase_ : Tuple = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowerCAmelCase_ : Dict = random_attention_mask([batch_size, 4] ) lowerCAmelCase_ : int = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def lowerCamelCase ( self : int , a_ : List[str] , a_ : Tuple ): lowerCAmelCase_ : List[str] = TFViTModel(a_ , name="vision_model" ) lowerCAmelCase_ : List[Any] = TFBertModel(a_ , name="text_model" ) return vision_model, text_model def lowerCamelCase ( self : List[Any] ): lowerCAmelCase_ : List[str] = TFViTModelTester(self ) lowerCAmelCase_ : Optional[int] = TFBertModelTester(self ) lowerCAmelCase_ : List[str] = vit_model_tester.prepare_config_and_inputs() lowerCAmelCase_ : Optional[int] = bert_model_tester.prepare_config_and_inputs() lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = vision_config_and_inputs ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) : Dict = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class __lowerCamelCase ( A__ , unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : Tuple ): # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's # just reinitialize it. lowerCAmelCase_ : Optional[Any] = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) lowerCAmelCase_ : Tuple = 13 lowerCAmelCase_ : int = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowerCAmelCase_ : int = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowerCAmelCase_ : Union[str, Any] = random_attention_mask([batch_size, 4] ) lowerCAmelCase_ : int = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def lowerCamelCase ( self : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : int , a_ : Dict=None , **a_ : int ): lowerCAmelCase_ , lowerCAmelCase_ : str = self.get_vision_text_model(a_ , a_ ) lowerCAmelCase_ : Any = TFVisionTextDualEncoderModel(vision_model=a_ , text_model=a_ ) lowerCAmelCase_ : str = model( input_ids=a_ , pixel_values=a_ , attention_mask=a_ , output_attentions=a_ ) lowerCAmelCase_ : Tuple = output.vision_model_output.attentions self.assertEqual(len(a_ ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) lowerCAmelCase_ : str = to_atuple(vision_model.config.image_size ) lowerCAmelCase_ : Optional[int] = to_atuple(vision_model.config.patch_size ) lowerCAmelCase_ : str = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowerCAmelCase_ : Optional[int] = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowerCAmelCase_ : List[Any] = output.text_model_output.attentions self.assertEqual(len(a_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def lowerCamelCase ( self : List[str] , a_ : Optional[Any] , a_ : List[str] ): lowerCAmelCase_ : int = TFDeiTModel(a_ , name="vision_model" ) lowerCAmelCase_ : Any = TFRobertaModel(a_ , name="text_model" ) return vision_model, text_model def lowerCamelCase ( self : Optional[int] ): lowerCAmelCase_ : Optional[Any] = TFDeiTModelTester(self ) lowerCAmelCase_ : List[Any] = TFRobertaModelTester(self ) lowerCAmelCase_ : List[str] = vit_model_tester.prepare_config_and_inputs() lowerCAmelCase_ : Tuple = bert_model_tester.prepare_config_and_inputs() lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Dict = vision_config_and_inputs ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) : Tuple = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class __lowerCamelCase ( A__ , unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : int ): lowerCAmelCase_ : Dict = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) lowerCAmelCase_ : int = 13 lowerCAmelCase_ : List[Any] = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowerCAmelCase_ : List[str] = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowerCAmelCase_ : Tuple = random_attention_mask([batch_size, 4] ) lowerCAmelCase_ : int = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def lowerCamelCase ( self : str , a_ : Any , a_ : Dict ): lowerCAmelCase_ : Union[str, Any] = TFCLIPVisionModel(a_ , name="vision_model" ) lowerCAmelCase_ : str = TFBertModel(a_ , name="text_model" ) return vision_model, text_model def lowerCamelCase ( self : Tuple ): lowerCAmelCase_ : str = TFCLIPVisionModelTester(self ) lowerCAmelCase_ : int = TFBertModelTester(self ) lowerCAmelCase_ : Optional[int] = clip_model_tester.prepare_config_and_inputs() lowerCAmelCase_ : List[str] = bert_model_tester.prepare_config_and_inputs() lowerCAmelCase_ , lowerCAmelCase_ : str = vision_config_and_inputs ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) : Optional[int] = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def lowerCamelCase ( self : Optional[int] ): lowerCAmelCase_ : Optional[Any] = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=a_ ) lowerCAmelCase_ : Tuple = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) lowerCAmelCase_ : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) lowerCAmelCase_ : str = processor( text=["una foto di un gatto", "una foto di un cane"] , images=a_ , padding=a_ , return_tensors="np" ) lowerCAmelCase_ : Any = model(**a_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) lowerCAmelCase_ : Dict = np.array([[1.2284727, 0.3104122]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , a_ , atol=1e-3 ) )
610
"""simple docstring""" lowercase__ = """ # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git """ lowercase__ = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowercase__ = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
610
1
import warnings from ..trainer import Trainer from ..utils import logging __lowercase : Union[str, Any] =logging.get_logger(__name__) class A ( __lowercase ): def __init__( self: int , _lowerCAmelCase: Any=None , **_lowerCAmelCase: Optional[Any] ) -> str: '''simple docstring''' warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , __A , ) super().__init__(args=__A , **__A )
711
from typing import 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 ....file_utils import PaddingStrategy, TensorType from ....utils import logging __lowercase : Union[str, Any] =logging.get_logger(__name__) class A ( __lowercase ): _snake_case =['''input_features''', '''attention_mask'''] def __init__( self: Dict , _lowerCAmelCase: List[str]=80 , _lowerCAmelCase: Optional[Any]=1_6000 , _lowerCAmelCase: Any=0.0 , _lowerCAmelCase: Optional[Any]=10 , _lowerCAmelCase: Optional[Any]=25 , _lowerCAmelCase: Union[str, Any]="hamming_window" , _lowerCAmelCase: Optional[int]=3_27_68.0 , _lowerCAmelCase: Optional[Any]=0.97 , _lowerCAmelCase: Any=1.0 , _lowerCAmelCase: List[str]=True , _lowerCAmelCase: Dict=True , _lowerCAmelCase: Any=False , **_lowerCAmelCase: Any , ) -> Dict: '''simple docstring''' super().__init__(feature_size=_lowerCAmelCase , sampling_rate=_lowerCAmelCase , padding_value=_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase_ =feature_size UpperCAmelCase_ =sampling_rate UpperCAmelCase_ =padding_value UpperCAmelCase_ =hop_length UpperCAmelCase_ =win_length UpperCAmelCase_ =frame_signal_scale UpperCAmelCase_ =preemphasis_coeff UpperCAmelCase_ =mel_floor UpperCAmelCase_ =normalize_means UpperCAmelCase_ =normalize_vars UpperCAmelCase_ =win_function UpperCAmelCase_ =return_attention_mask UpperCAmelCase_ =win_length * sampling_rate // 1000 UpperCAmelCase_ =hop_length * sampling_rate // 1000 UpperCAmelCase_ =optimal_fft_length(self.sample_size ) UpperCAmelCase_ =(self.n_fft // 2) + 1 def lowerCAmelCase__ ( self: Optional[Any] , _lowerCAmelCase: np.array ) -> np.ndarray: '''simple docstring''' if self.win_function == "hamming_window": UpperCAmelCase_ =window_function(window_length=self.sample_size , name=self.win_function , periodic=_lowerCAmelCase ) else: UpperCAmelCase_ =window_function(window_length=self.sample_size , name=self.win_function ) UpperCAmelCase_ =mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) UpperCAmelCase_ =spectrogram( one_waveform * self.frame_signal_scale , window=_lowerCAmelCase , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=_lowerCAmelCase , preemphasis=self.preemphasis_coeff , mel_filters=_lowerCAmelCase , mel_floor=self.mel_floor , log_mel="log" , ) return msfc_features.T def lowerCAmelCase__ ( self: Dict , _lowerCAmelCase: List[Any] , _lowerCAmelCase: Dict , _lowerCAmelCase: Any ) -> Any: '''simple docstring''' if self.normalize_means: UpperCAmelCase_ =x[:input_length].mean(axis=0 ) UpperCAmelCase_ =np.subtract(_lowerCAmelCase , _lowerCAmelCase ) if self.normalize_vars: UpperCAmelCase_ =x[:input_length].std(axis=0 ) UpperCAmelCase_ =np.divide(_lowerCAmelCase , _lowerCAmelCase ) if input_length < x.shape[0]: UpperCAmelCase_ =padding_value # make sure array is in float32 UpperCAmelCase_ =x.astype(np.floataa ) return x def lowerCAmelCase__ ( self: List[str] , _lowerCAmelCase: List[np.ndarray] , _lowerCAmelCase: Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' UpperCAmelCase_ =attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(_lowerCAmelCase , _lowerCAmelCase , self.padding_value ) for x, n in zip(_lowerCAmelCase , _lowerCAmelCase )] def __call__( self: int , _lowerCAmelCase: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , _lowerCAmelCase: Union[bool, str, PaddingStrategy] = False , _lowerCAmelCase: Optional[int] = None , _lowerCAmelCase: bool = False , _lowerCAmelCase: Optional[int] = None , _lowerCAmelCase: Optional[bool] = None , _lowerCAmelCase: Optional[Union[str, TensorType]] = None , _lowerCAmelCase: Optional[int] = None , **_lowerCAmelCase: List[Any] , ) -> BatchFeature: '''simple docstring''' 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 `raw_speech` 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." ) UpperCAmelCase_ =isinstance(_lowerCAmelCase , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F'Only mono-channel audio is supported for input to {self}' ) UpperCAmelCase_ =is_batched_numpy or ( isinstance(_lowerCAmelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: UpperCAmelCase_ =[np.asarray(_lowerCAmelCase , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCAmelCase , np.ndarray ): UpperCAmelCase_ =np.asarray(_lowerCAmelCase , dtype=np.floataa ) elif isinstance(_lowerCAmelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): UpperCAmelCase_ =raw_speech.astype(np.floataa ) # always return batch if not is_batched: UpperCAmelCase_ =[raw_speech] # extract fbank features UpperCAmelCase_ =[self._extract_mfsc_features(_lowerCAmelCase ) for one_waveform in raw_speech] # convert into correct format for padding UpperCAmelCase_ =BatchFeature({"input_features": features} ) UpperCAmelCase_ =self.pad( _lowerCAmelCase , padding=_lowerCAmelCase , max_length=_lowerCAmelCase , truncation=_lowerCAmelCase , pad_to_multiple_of=_lowerCAmelCase , return_attention_mask=_lowerCAmelCase , **_lowerCAmelCase , ) # make sure list is in array format UpperCAmelCase_ =padded_inputs.get("input_features" ) if isinstance(input_features[0] , _lowerCAmelCase ): UpperCAmelCase_ =[np.asarray(_lowerCAmelCase , dtype=np.floataa ) for feature in input_features] UpperCAmelCase_ =padded_inputs.get("attention_mask" ) if attention_mask is not None: UpperCAmelCase_ =[np.asarray(_lowerCAmelCase , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: UpperCAmelCase_ =( np.array(_lowerCAmelCase , dtype=np.intaa ) if self._get_padding_strategies(_lowerCAmelCase , max_length=_lowerCAmelCase ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) UpperCAmelCase_ =self.normalize( padded_inputs["input_features"] , attention_mask=_lowerCAmelCase ) if return_tensors is not None: UpperCAmelCase_ =padded_inputs.convert_to_tensors(_lowerCAmelCase ) return padded_inputs
550
0
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def UpperCamelCase_ ( lowerCAmelCase__ = 8 ): """simple docstring""" _lowerCAmelCase : str = ascii_letters + digits + punctuation return "".join(secrets.choice(UpperCAmelCase_ ) for _ in range(UpperCAmelCase_ ) ) def UpperCamelCase_ ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" i -= len(UpperCAmelCase_ ) _lowerCAmelCase : Any = i // 3 _lowerCAmelCase : Optional[Any] = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) _lowerCAmelCase : int = ( chars_incl + random(UpperCAmelCase_ , quotient + remainder ) + random(UpperCAmelCase_ , UpperCAmelCase_ ) + random(UpperCAmelCase_ , UpperCAmelCase_ ) ) _lowerCAmelCase : Optional[int] = list(UpperCAmelCase_ ) shuffle(UpperCAmelCase_ ) return "".join(UpperCAmelCase_ ) # random is a generalised function for letters, characters and numbers def UpperCamelCase_ ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" return "".join(secrets.choice(UpperCAmelCase_ ) for _ in range(UpperCAmelCase_ ) ) def UpperCamelCase_ ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" pass # Put your code here... def UpperCamelCase_ ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" pass # Put your code here... def UpperCamelCase_ ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" pass # Put your code here... def UpperCamelCase_ ( lowerCAmelCase__ , lowerCAmelCase__ = 8 ): """simple docstring""" if len(UpperCAmelCase_ ) < min_length: # Your Password must be at least 8 characters long return False _lowerCAmelCase : List[str] = any(char in ascii_uppercase for char in password ) _lowerCAmelCase : Union[str, Any] = any(char in ascii_lowercase for char in password ) _lowerCAmelCase : List[Any] = any(char in digits for char in password ) _lowerCAmelCase : str = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def UpperCamelCase_ ( ): """simple docstring""" _lowerCAmelCase : Any = int(input("Please indicate the max length of your password: " ).strip() ) _lowerCAmelCase : Any = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:" , password_generator(UpperCAmelCase_ ) ) print( "Alternative Password generated:" , alternative_password_generator(UpperCAmelCase_ , UpperCAmelCase_ ) , ) print("[If you are thinking of using this passsword, You better save it.]" ) if __name__ == "__main__": main()
424
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets _lowercase = """\ @inproceedings{lin-2004-rouge, title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\", author = \"Lin, Chin-Yew\", booktitle = \"Text Summarization Branches Out\", month = jul, year = \"2004\", address = \"Barcelona, Spain\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W04-1013\", pages = \"74--81\", } """ _lowercase = """\ ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters. This metrics is a wrapper around Google Research reimplementation of ROUGE: https://github.com/google-research/google-research/tree/master/rouge """ _lowercase = """ Calculates average rouge scores for a list of hypotheses and references Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. rouge_types: A list of rouge types to calculate. Valid names: `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring, `\"rougeL\"`: Longest common subsequence based scoring. `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`. See details in https://github.com/huggingface/datasets/issues/617 use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes. use_aggregator: Return aggregates if this is set to True Returns: rouge1: rouge_1 (precision, recall, f1), rouge2: rouge_2 (precision, recall, f1), rougeL: rouge_l (precision, recall, f1), rougeLsum: rouge_lsum (precision, recall, f1) Examples: >>> rouge = datasets.load_metric('rouge') >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> results = rouge.compute(predictions=predictions, references=references) >>> print(list(results.keys())) ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] >>> print(results[\"rouge1\"]) AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0)) >>> print(results[\"rouge1\"].mid.fmeasure) 1.0 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase_ ( datasets.Metric ): def _snake_case ( self ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/google-research/google-research/tree/master/rouge'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/ROUGE_(metric)''', '''https://github.com/google-research/google-research/tree/master/rouge''', ] , ) def _snake_case ( self , __A , __A , __A=None , __A=True , __A=False ) -> List[str]: if rouge_types is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] =['''rouge1''', '''rouge2''', '''rougeL''', '''rougeLsum'''] SCREAMING_SNAKE_CASE_ : Tuple =rouge_scorer.RougeScorer(rouge_types=__A , use_stemmer=__A ) if use_aggregator: SCREAMING_SNAKE_CASE_ : List[str] =scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE_ : Tuple =[] for ref, pred in zip(__A , __A ): SCREAMING_SNAKE_CASE_ : int =scorer.score(__A , __A ) if use_aggregator: aggregator.add_scores(__A ) else: scores.append(__A ) if use_aggregator: SCREAMING_SNAKE_CASE_ : Tuple =aggregator.aggregate() else: SCREAMING_SNAKE_CASE_ : Optional[int] ={} for key in scores[0]: SCREAMING_SNAKE_CASE_ : Tuple =[score[key] for score in scores] return result
443
0
import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[str] = DownBlockaD # noqa F405 _UpperCAmelCase :Dict = 'down' def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [-0.02_32, -0.98_69, 0.80_54, -0.06_37, -0.16_88, -1.42_64, 0.44_70, -1.33_94, 0.09_04] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Any = ResnetDownsampleBlockaD # noqa F405 _UpperCAmelCase :Any = 'down' def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [0.07_10, 0.24_10, -0.73_20, -1.07_57, -1.13_43, 0.35_40, -0.01_33, -0.25_76, 0.09_48] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[int] = AttnDownBlockaD # noqa F405 _UpperCAmelCase :Optional[int] = 'down' def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = [0.06_36, 0.89_64, -0.62_34, -1.01_31, 0.08_44, 0.49_35, 0.34_37, 0.09_11, -0.29_57] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[Any] = CrossAttnDownBlockaD # noqa F405 _UpperCAmelCase :List[Any] = 'down' def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = super().prepare_init_args_and_inputs_for_common() UpperCamelCase : Optional[Any] = 32 return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = [0.22_38, -0.73_96, -0.22_55, -0.38_29, 0.19_25, 1.16_65, 0.06_03, -0.72_95, 0.19_83] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Dict = SimpleCrossAttnDownBlockaD # noqa F405 _UpperCAmelCase :List[Any] = 'down' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_encoder_hidden_states=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = super().prepare_init_args_and_inputs_for_common() UpperCamelCase : Union[str, Any] = 32 return init_dict, inputs_dict @unittest.skipIf(torch_device == "mps" , "MPS result is not consistent" ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = [0.79_21, -0.09_92, -0.19_62, -0.76_95, -0.42_42, 0.78_04, 0.47_37, 0.27_65, 0.33_38] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[Any] = SkipDownBlockaD # noqa F405 _UpperCAmelCase :Dict = 'down' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_skip_sample=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = [-0.08_45, -0.20_87, -0.24_65, 0.09_71, 0.19_00, -0.04_84, 0.26_64, 0.41_79, 0.50_69] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Dict = AttnSkipDownBlockaD # noqa F405 _UpperCAmelCase :Any = 'down' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_skip_sample=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = [0.55_39, 0.16_09, 0.49_24, 0.05_37, -0.19_95, 0.40_50, 0.09_79, -0.27_21, -0.06_42] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[str] = DownEncoderBlockaD # noqa F405 _UpperCAmelCase :Optional[int] = 'down' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_temb=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = { "in_channels": 32, "out_channels": 32, } UpperCamelCase : Union[str, Any] = self.dummy_input return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [1.11_02, 0.53_02, 0.48_72, -0.00_23, -0.80_42, 0.04_83, -0.34_89, -0.56_32, 0.76_26] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[Any] = AttnDownEncoderBlockaD # noqa F405 _UpperCAmelCase :Optional[int] = 'down' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_temb=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = { "in_channels": 32, "out_channels": 32, } UpperCamelCase : Optional[int] = self.dummy_input return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = [0.89_66, -0.14_86, 0.85_68, 0.81_41, -0.90_46, -0.13_42, -0.09_72, -0.74_17, 0.15_38] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = UNetMidBlockaD # noqa F405 _UpperCAmelCase :Optional[Any] = 'mid' def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = { "in_channels": 32, "temb_channels": 128, } UpperCamelCase : List[Any] = self.dummy_input return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = [-0.10_62, 1.72_48, 0.34_94, 1.45_69, -0.09_10, -1.24_21, -0.99_84, 0.67_36, 1.00_28] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[int] = UNetMidBlockaDCrossAttn # noqa F405 _UpperCAmelCase :Optional[Any] = 'mid' def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = super().prepare_init_args_and_inputs_for_common() UpperCamelCase : Dict = 32 return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = [0.01_87, 2.42_20, 0.44_84, 1.12_03, -0.61_21, -1.51_22, -0.82_70, 0.78_51, 1.83_35] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :int = UNetMidBlockaDSimpleCrossAttn # noqa F405 _UpperCAmelCase :Optional[Any] = 'mid' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_encoder_hidden_states=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = super().prepare_init_args_and_inputs_for_common() UpperCamelCase : Tuple = 32 return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = [0.71_43, 1.99_74, 0.54_48, 1.39_77, 0.12_82, -1.12_37, -1.42_38, 0.55_30, 0.88_80] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = UpBlockaD # noqa F405 _UpperCAmelCase :Dict = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = [-0.20_41, -0.41_65, -0.30_22, 0.00_41, -0.66_28, -0.70_53, 0.19_28, -0.03_25, 0.05_23] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :str = ResnetUpsampleBlockaD # noqa F405 _UpperCAmelCase :Tuple = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = [0.22_87, 0.35_49, -0.13_46, 0.47_97, -0.17_15, -0.96_49, 0.73_05, -0.58_64, -0.62_44] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[int] = CrossAttnUpBlockaD # noqa F405 _UpperCAmelCase :Dict = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = super().prepare_init_args_and_inputs_for_common() UpperCamelCase : int = 32 return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = [-0.14_03, -0.35_15, -0.04_20, -0.14_25, 0.31_67, 0.50_94, -0.21_81, 0.59_31, 0.55_82] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[Any] = SimpleCrossAttnUpBlockaD # noqa F405 _UpperCAmelCase :Optional[Any] = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=A_ , include_encoder_hidden_states=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = super().prepare_init_args_and_inputs_for_common() UpperCamelCase : Optional[Any] = 32 return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = [0.26_45, 0.14_80, 0.09_09, 0.80_44, -0.97_58, -0.90_83, 0.09_94, -1.14_53, -0.74_02] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :List[Any] = AttnUpBlockaD # noqa F405 _UpperCAmelCase :Any = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=A_ ) @unittest.skipIf(torch_device == "mps" , "MPS result is not consistent" ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = [0.09_79, 0.13_26, 0.00_21, 0.06_59, 0.22_49, 0.00_59, 0.11_32, 0.59_52, 0.10_33] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[int] = SkipUpBlockaD # noqa F405 _UpperCAmelCase :int = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [-0.08_93, -0.12_34, -0.15_06, -0.03_32, 0.01_23, -0.02_11, 0.05_66, 0.01_43, 0.03_62] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :int = AttnSkipUpBlockaD # noqa F405 _UpperCAmelCase :Any = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_res_hidden_states_tuple=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = [0.03_61, 0.06_17, 0.27_87, -0.03_50, 0.03_42, 0.34_21, -0.08_43, 0.09_13, 0.30_15] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[Any] = UpDecoderBlockaD # noqa F405 _UpperCAmelCase :str = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_temb=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = {"in_channels": 32, "out_channels": 32} UpperCamelCase : Any = self.dummy_input return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = [0.44_04, 0.19_98, -0.98_86, -0.33_20, -0.31_28, -0.70_34, -0.69_55, -0.23_38, -0.31_37] super().test_output(A_ ) class A__ ( __snake_case , unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = AttnUpDecoderBlockaD # noqa F405 _UpperCAmelCase :Union[str, Any] = 'up' @property def __UpperCamelCase( self ): '''simple docstring''' return super().get_dummy_input(include_temb=A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = {"in_channels": 32, "out_channels": 32} UpperCamelCase : List[Any] = self.dummy_input return init_dict, inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = [0.67_38, 0.44_91, 0.10_55, 1.07_10, 0.73_16, 0.33_39, 0.33_52, 0.10_23, 0.35_68] super().test_output(A_ )
720
import math import tensorflow as tf from packaging import version def A_ ( _lowerCAmelCase ) -> Any: UpperCamelCase : List[Any] = tf.convert_to_tensor(_lowerCAmelCase ) UpperCamelCase : Any = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def A_ ( _lowerCAmelCase ) -> Dict: UpperCamelCase : Union[str, Any] = tf.convert_to_tensor(_lowerCAmelCase ) UpperCamelCase : List[Any] = tf.cast(math.pi , x.dtype ) UpperCamelCase : Optional[Any] = tf.cast(0.044_715 , x.dtype ) UpperCamelCase : int = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(_lowerCAmelCase , 3 )) )) return x * cdf def A_ ( _lowerCAmelCase ) -> List[Any]: UpperCamelCase : str = tf.convert_to_tensor(_lowerCAmelCase ) return x * tf.tanh(tf.math.softplus(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase ) -> List[Any]: UpperCamelCase : Tuple = tf.convert_to_tensor(_lowerCAmelCase ) UpperCamelCase : List[Any] = tf.cast(0.044_715 , x.dtype ) UpperCamelCase : Optional[Any] = tf.cast(0.7_978_845_608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def A_ ( _lowerCAmelCase ) -> Optional[Any]: UpperCamelCase : Any = tf.convert_to_tensor(_lowerCAmelCase ) UpperCamelCase : List[Any] = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def A_ ( _lowerCAmelCase ) -> List[Any]: return tf.clip_by_value(_gelu(_lowerCAmelCase ) , -10 , 10 ) def A_ ( _lowerCAmelCase , _lowerCAmelCase=-1 ) -> str: UpperCamelCase , UpperCamelCase : List[Any] = tf.split(_lowerCAmelCase , 2 , axis=_lowerCAmelCase ) return a * tf.math.sigmoid(_lowerCAmelCase ) if version.parse(tf.version.VERSION) >= version.parse("""2.4"""): def A_ ( _lowerCAmelCase ) -> Any: return tf.keras.activations.gelu(_lowerCAmelCase , approximate=_lowerCAmelCase ) __lowerCamelCase : Optional[int] = tf.keras.activations.gelu __lowerCamelCase : int = approximate_gelu_wrap else: __lowerCamelCase : List[Any] = _gelu __lowerCamelCase : Optional[Any] = _gelu_new __lowerCamelCase : Any = { """gelu""": gelu, """gelu_10""": gelu_aa, """gelu_fast""": gelu_fast, """gelu_new""": gelu_new, """glu""": glu, """mish""": mish, """quick_gelu""": quick_gelu, """relu""": tf.keras.activations.relu, """sigmoid""": tf.keras.activations.sigmoid, """silu""": tf.keras.activations.swish, """swish""": tf.keras.activations.swish, """tanh""": tf.keras.activations.tanh, } def A_ ( _lowerCAmelCase ) -> Optional[Any]: if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(F"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )
38
0
"""simple docstring""" import re from filelock import FileLock try: import nltk UpperCAmelCase : Tuple = True except (ImportError, ModuleNotFoundError): UpperCAmelCase : Optional[int] = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase ( _UpperCamelCase : str ) -> str: '''simple docstring''' re.sub("""<n>""" , """""" , _UpperCamelCase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_UpperCamelCase ) )
139
"""simple docstring""" def lowerCamelCase ( _UpperCamelCase : int = 1_0_0_0_0_0_0 ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = 1 __UpperCAmelCase : Union[str, Any] = 1 __UpperCAmelCase : Optional[Any] = {1: 1} for inputa in range(2 , _UpperCamelCase ): __UpperCAmelCase : Optional[int] = 0 __UpperCAmelCase : str = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: __UpperCAmelCase : Tuple = (3 * number) + 1 counter += 1 if inputa not in counters: __UpperCAmelCase : Optional[Any] = counter if counter > pre_counter: __UpperCAmelCase : List[Any] = inputa __UpperCAmelCase : List[Any] = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
139
1
from __future__ import annotations import typing from collections import Counter def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> typing.Counter[int]: UpperCAmelCase_ : typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(a_, max_perimeter + 1 ): UpperCAmelCase_ : Any = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(a_ ): UpperCAmelCase_ : List[Any] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 1000 ) -> int: UpperCAmelCase_ : Dict = pythagorean_triple(a_ ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
713
'''simple docstring''' import sys import turtle def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : int, ) -> None: my_pen.up() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) if depth == 0: return triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), 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>" ) snake_case_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") snake_case_ : Tuple = [(-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]))
644
0
import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version A : Any = logging.getLogger(__name__) require_version('pytorch_lightning>=1.0.4') A : List[Any] = { """base""": AutoModel, """sequence-classification""": AutoModelForSequenceClassification, """question-answering""": AutoModelForQuestionAnswering, """pretraining""": AutoModelForPreTraining, """token-classification""": AutoModelForTokenClassification, """language-modeling""": AutoModelWithLMHead, """summarization""": AutoModelForSeqaSeqLM, """translation""": AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization A : Union[str, Any] = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } A : Union[str, Any] = sorted(arg_to_scheduler.keys()) A : Tuple = """{""" + """, """.join(arg_to_scheduler_choices) + """}""" class __A( pl.LightningModule ): def __init__( self , _snake_case , _snake_case=None , _snake_case="base" , _snake_case=None , _snake_case=None , _snake_case=None , **_snake_case , ) -> str: '''simple docstring''' super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(__lowerCamelCase ) __a = 0 __a = Path(self.hparams.output_dir ) __a = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: __a = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({'''num_labels''': num_labels} if num_labels is not None else {}) , cache_dir=__lowerCamelCase , **__lowerCamelCase , ) else: __a = config __a = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(self.hparams , __lowerCamelCase , __lowerCamelCase ): assert hasattr(self.config , __lowerCamelCase ), F"""model config doesn't have a `{p}` attribute""" setattr(self.config , __lowerCamelCase , getattr(self.hparams , __lowerCamelCase ) ) if tokenizer is None: __a = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=__lowerCamelCase , ) else: __a = tokenizer __a = MODEL_MODES[mode] if model is None: __a = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool('''.ckpt''' in self.hparams.model_name_or_path ) , config=self.config , cache_dir=__lowerCamelCase , ) else: __a = model def SCREAMING_SNAKE_CASE_ ( self , *_snake_case , **_snake_case ) -> Optional[int]: '''simple docstring''' __a = self.model_type.from_pretrained(*__lowerCamelCase , **__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' __a = arg_to_scheduler[self.hparams.lr_scheduler] __a = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) __a = {'''scheduler''': scheduler, '''interval''': '''step''', '''frequency''': 1} return scheduler def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = self.model __a = ['''bias''', '''LayerNorm.weight'''] __a = [ { '''params''': [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters '''weight_decay''': self.hparams.weight_decay, }, { '''params''': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], '''weight_decay''': 0.0, }, ] if self.hparams.adafactor: __a = Adafactor( __lowerCamelCase , lr=self.hparams.learning_rate , scale_parameter=__lowerCamelCase , relative_step=__lowerCamelCase ) else: __a = AdamW( __lowerCamelCase , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) __a = optimizer __a = self.get_lr_scheduler() return [optimizer], [scheduler] def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Any: '''simple docstring''' return self.validation_step(__lowerCamelCase , __lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Union[str, Any]: '''simple docstring''' return self.validation_end(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' __a = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores __a = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Union[str, Any]: '''simple docstring''' if stage == "test": __a = len(self.test_dataloader().dataset ) else: __a = self.get_dataloader('''train''' , self.hparams.train_batch_size , shuffle=__lowerCamelCase ) __a = len(self.train_dataloader().dataset ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case = False ) -> str: '''simple docstring''' raise NotImplementedError('''You must implement this for your task''' ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' return self.train_loader def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' return self.get_dataloader('''dev''' , self.hparams.eval_batch_size , shuffle=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' return self.get_dataloader('''test''' , self.hparams.eval_batch_size , shuffle=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> List[str]: '''simple docstring''' return os.path.join( self.hparams.data_dir , '''cached_{}_{}_{}'''.format( __lowerCamelCase , list(filter(__lowerCamelCase , self.hparams.model_name_or_path.split('''/''' ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> List[Any]: '''simple docstring''' __a = self.output_dir.joinpath('''best_tfmr''' ) __a = self.step_count self.model.save_pretrained(__lowerCamelCase ) self.tokenizer.save_pretrained(__lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _snake_case , _snake_case ) -> List[str]: '''simple docstring''' parser.add_argument( '''--model_name_or_path''' , default=__lowerCamelCase , type=__lowerCamelCase , required=__lowerCamelCase , help='''Path to pretrained model or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--config_name''' , default='''''' , type=__lowerCamelCase , help='''Pretrained config name or path if not the same as model_name''' ) parser.add_argument( '''--tokenizer_name''' , default=__lowerCamelCase , type=__lowerCamelCase , help='''Pretrained tokenizer name or path if not the same as model_name''' , ) parser.add_argument( '''--cache_dir''' , default=str(Path(__lowerCamelCase ).parent / '''test_run''' / '''cache''' ) , type=__lowerCamelCase , help='''Where do you want to store the pre-trained models downloaded from huggingface.co''' , ) parser.add_argument( '''--encoder_layerdrop''' , type=__lowerCamelCase , help='''Encoder layer dropout probability (Optional). Goes into model.config''' , ) parser.add_argument( '''--decoder_layerdrop''' , type=__lowerCamelCase , help='''Decoder layer dropout probability (Optional). Goes into model.config''' , ) parser.add_argument( '''--dropout''' , type=__lowerCamelCase , help='''Dropout probability (Optional). Goes into model.config''' , ) parser.add_argument( '''--attention_dropout''' , type=__lowerCamelCase , help='''Attention dropout probability (Optional). Goes into model.config''' , ) parser.add_argument('''--learning_rate''' , default=5E-5 , type=__lowerCamelCase , help='''The initial learning rate for Adam.''' ) parser.add_argument( '''--lr_scheduler''' , default='''linear''' , choices=__lowerCamelCase , metavar=__lowerCamelCase , type=__lowerCamelCase , help='''Learning rate scheduler''' , ) parser.add_argument('''--weight_decay''' , default=0.0 , type=__lowerCamelCase , help='''Weight decay if we apply some.''' ) parser.add_argument('''--adam_epsilon''' , default=1E-8 , type=__lowerCamelCase , help='''Epsilon for Adam optimizer.''' ) parser.add_argument('''--warmup_steps''' , default=0 , type=__lowerCamelCase , help='''Linear warmup over warmup_steps.''' ) parser.add_argument('''--num_workers''' , default=4 , type=__lowerCamelCase , help='''kwarg passed to DataLoader''' ) parser.add_argument('''--num_train_epochs''' , dest='''max_epochs''' , default=3 , type=__lowerCamelCase ) parser.add_argument('''--train_batch_size''' , default=32 , type=__lowerCamelCase ) parser.add_argument('''--eval_batch_size''' , default=32 , type=__lowerCamelCase ) parser.add_argument('''--adafactor''' , action='''store_true''' ) class __A( pl.Callback ): def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Optional[int]: '''simple docstring''' if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class __A( pl.Callback ): def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Optional[int]: '''simple docstring''' for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(__lowerCamelCase ) class __A( pl.Callback ): def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> List[str]: '''simple docstring''' __a = trainer.lr_schedulers[0]['''scheduler'''] __a = {F"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> List[Any]: '''simple docstring''' rank_zero_info('''***** Validation results *****''' ) __a = trainer.callback_metrics # Log results for key in sorted(__lowerCamelCase ): if key not in ["log", "progress_bar"]: rank_zero_info('''{} = {}\n'''.format(__lowerCamelCase , str(metrics[key] ) ) ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Any: '''simple docstring''' rank_zero_info('''***** Test results *****''' ) __a = trainer.callback_metrics # Log and save results to file __a = os.path.join(pl_module.hparams.output_dir , '''test_results.txt''' ) with open(__lowerCamelCase , '''w''' ) as writer: for key in sorted(__lowerCamelCase ): if key not in ["log", "progress_bar"]: rank_zero_info('''{} = {}\n'''.format(__lowerCamelCase , str(metrics[key] ) ) ) writer.write('''{} = {}\n'''.format(__lowerCamelCase , str(metrics[key] ) ) ) def __lowerCAmelCase ( a__ , a__ ) -> Union[str, Any]: # To allow all pl args uncomment the following line # parser = pl.Trainer.add_argparse_args(parser) parser.add_argument( '''--output_dir''' , default=str(Path(__lowerCAmelCase ).parent / '''test_run''' / '''model_checkpoints''' ) , type=__lowerCAmelCase , help='''The output directory where the model predictions and checkpoints will be written.''' , ) parser.add_argument( '''--fp16''' , action='''store_true''' , help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit''' , ) parser.add_argument( '''--fp16_opt_level''' , type=__lowerCAmelCase , default='''O2''' , help=( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].''' '''See details at https://nvidia.github.io/apex/amp.html''' ) , ) parser.add_argument('''--n_tpu_cores''' , dest='''tpu_cores''' , type=__lowerCAmelCase ) parser.add_argument('''--max_grad_norm''' , dest='''gradient_clip_val''' , default=1.0 , type=__lowerCAmelCase , help='''Max gradient norm''' ) parser.add_argument('''--do_train''' , action='''store_true''' , help='''Whether to run training.''' ) parser.add_argument('''--do_predict''' , action='''store_true''' , help='''Whether to run predictions on the test set.''' ) parser.add_argument( '''--gradient_accumulation_steps''' , dest='''accumulate_grad_batches''' , type=__lowerCAmelCase , default=1 , help='''Number of updates steps to accumulate before performing a backward/update pass.''' , ) parser.add_argument('''--seed''' , type=__lowerCAmelCase , default=42 , help='''random seed for initialization''' ) parser.add_argument( '''--data_dir''' , default=str(Path(__lowerCAmelCase ).parent / '''test_run''' / '''dummy-train-data''' ) , type=__lowerCAmelCase , help='''The input data dir. Should contain the training files for the CoNLL-2003 NER task.''' , ) def __lowerCAmelCase ( a__ , a__ , a__=None , a__=True , a__=[] , a__=None , a__=None , **a__ , ) -> Optional[int]: pl.seed_everything(args.seed ) # init model __a = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=__lowerCAmelCase ) # add custom checkpoints if checkpoint_callback is None: __a = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix='''checkpoint''' , monitor='''val_loss''' , mode='''min''' , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(__lowerCAmelCase ) if logging_callback is None: __a = LoggingCallback() __a = {} if args.fpaa: __a = 16 if args.gpus > 1: __a = '''auto''' __a = '''ddp''' __a = args.accumulate_grad_batches __a = None __a = '''auto''' __a = pl.Trainer.from_argparse_args( __lowerCAmelCase , weights_summary=__lowerCAmelCase , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=__lowerCAmelCase , val_check_interval=1 , num_sanity_val_steps=2 , **__lowerCAmelCase , ) if args.do_train: trainer.fit(__lowerCAmelCase ) else: print('''RAG modeling tests with new set functions successfuly executed!''' ) return trainer
219
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __magic_name__ : Any = { """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: __magic_name__ : List[str] = ["""LayoutLMv2TokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Any = ["""LayoutLMv2FeatureExtractor"""] __magic_name__ : Any = ["""LayoutLMv2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Any = [ """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 __magic_name__ : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
615
0
"""simple docstring""" import argparse import os import re import packaging.version a_ = '''examples/''' a_ = { '''examples''': (re.compile(r'''^check_min_version\(\"[^\"]+\"\)\s*$''', re.MULTILINE), '''check_min_version(\"VERSION\")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+\"([^\"]+)\"\s*$''', re.MULTILINE), '''__version__ = \"VERSION\"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*\"[^\"]+\",''', re.MULTILINE), r'''\1version=\"VERSION\",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*\"[^\"]+\"$''', re.MULTILINE), '''release = \"VERSION\"\n'''), } a_ = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } a_ = '''README.md''' def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): """simple docstring""" with open(snake_case_ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ : Optional[Any] = f.read() snake_case_ : Tuple = REPLACE_PATTERNS[pattern] snake_case_ : Union[str, Any] = replace.replace("""VERSION""" , snake_case_ ) snake_case_ : Dict = re_pattern.sub(snake_case_ , snake_case_ ) with open(snake_case_ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Optional[int] ): """simple docstring""" for folder, directories, fnames in os.walk(snake_case_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(snake_case_ , snake_case_ ) , snake_case_ , pattern="""examples""" ) def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int=False ): """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(snake_case_ , snake_case_ , snake_case_ ) if not patch: update_version_in_examples(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( ): """simple docstring""" snake_case_ : Any = """🤗 Transformers currently provides the following architectures""" snake_case_ : int = """1. Want to contribute a new model?""" with open(snake_case_ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ : Union[str, Any] = f.readlines() # Find the start of the list. snake_case_ : Dict = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 snake_case_ : Any = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): snake_case_ : Optional[int] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(snake_case_ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( ): """simple docstring""" with open(REPLACE_FILES["""init"""] , """r""" ) as f: snake_case_ : Dict = f.read() snake_case_ : str = REPLACE_PATTERNS["""init"""][0].search(snake_case_ ).groups()[0] return packaging.version.parse(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Optional[Any]=False ): """simple docstring""" snake_case_ : Dict = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: snake_case_ : Optional[Any] = default_version.base_version elif patch: snake_case_ : Any = f'{default_version.major}.{default_version.minor}.{default_version.micro + 1}' else: snake_case_ : str = f'{default_version.major}.{default_version.minor + 1}.0' # Now let's ask nicely if that's the right one. snake_case_ : Dict = input(f'Which version are you releasing? [{default_version}]' ) if len(snake_case_ ) == 0: snake_case_ : List[str] = default_version print(f'Updating version to {version}.' ) global_version_update(snake_case_ , patch=snake_case_ ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def SCREAMING_SNAKE_CASE__ ( ): """simple docstring""" snake_case_ : List[str] = get_version() snake_case_ : Union[str, Any] = f'{current_version.major}.{current_version.minor + 1}.0.dev0' snake_case_ : List[str] = current_version.base_version # Check with the user we got that right. snake_case_ : Union[str, Any] = input(f'Which version are we developing now? [{dev_version}]' ) if len(snake_case_ ) == 0: snake_case_ : Union[str, Any] = dev_version print(f'Updating version to {version}.' ) global_version_update(snake_case_ ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') a_ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
709
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING a_ = logging.get_logger(__name__) class __lowercase ( _UpperCAmelCase): """simple docstring""" _A : Optional[int] = """upernet""" def __init__(self , lowercase__=None , lowercase__=5_12 , lowercase__=0.02 , lowercase__=[1, 2, 3, 6] , lowercase__=True , lowercase__=0.4 , lowercase__=3_84 , lowercase__=2_56 , lowercase__=1 , lowercase__=False , lowercase__=2_55 , **lowercase__ , ): super().__init__(**lowercase__ ) 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=["""stage1""", """stage2""", """stage3""", """stage4"""] ) elif isinstance(lowercase__ , lowercase__ ): snake_case_ : Tuple = backbone_config.get("""model_type""" ) snake_case_ : List[str] = CONFIG_MAPPING[backbone_model_type] snake_case_ : List[Any] = config_class.from_dict(lowercase__ ) snake_case_ : List[Any] = backbone_config snake_case_ : Optional[Any] = hidden_size snake_case_ : Any = initializer_range snake_case_ : str = pool_scales snake_case_ : Dict = use_auxiliary_head snake_case_ : str = auxiliary_loss_weight snake_case_ : List[str] = auxiliary_in_channels snake_case_ : Optional[Any] = auxiliary_channels snake_case_ : Any = auxiliary_num_convs snake_case_ : List[Any] = auxiliary_concat_input snake_case_ : List[str] = loss_ignore_index def __UpperCamelCase (self ): snake_case_ : Dict = copy.deepcopy(self.__dict__ ) snake_case_ : Union[str, Any] = self.backbone_config.to_dict() snake_case_ : Any = self.__class__.model_type return output
48
0
"""simple docstring""" from torch import nn def _snake_case ( snake_case__ : Union[str, Any] ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'Unsupported activation function: {act_fn}' )
91
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class _snake_case ( lowercase_ ): lowerCAmelCase_ : torch.FloatTensor class _snake_case ( nn.Module ): def __init__( self , a__=3 , a__=3 , a__=("DownEncoderBlock2D",) , a__=(64,) , a__=2 , a__=32 , a__="silu" , a__=True , ) -> Union[str, Any]: '''simple docstring''' super().__init__() snake_case_ = layers_per_block snake_case_ = torch.nn.Convad( a__ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case_ = None snake_case_ = nn.ModuleList([] ) # down snake_case_ = block_out_channels[0] for i, down_block_type in enumerate(a__ ): snake_case_ = output_channel snake_case_ = block_out_channels[i] snake_case_ = i == len(a__ ) - 1 snake_case_ = get_down_block( a__ , num_layers=self.layers_per_block , in_channels=a__ , out_channels=a__ , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=a__ , resnet_groups=a__ , attention_head_dim=a__ , temb_channels=a__ , ) self.down_blocks.append(a__ ) # mid snake_case_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=a__ , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=a__ , temb_channels=a__ , ) # out snake_case_ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=a__ , eps=1e-6 ) snake_case_ = nn.SiLU() snake_case_ = 2 * out_channels if double_z else out_channels snake_case_ = nn.Convad(block_out_channels[-1] , a__ , 3 , padding=1 ) snake_case_ = False def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' snake_case_ = x snake_case_ = self.conv_in(a__ ) if self.training and self.gradient_checkpointing: def create_custom_forward(a__ ): def custom_forward(*a__ ): return module(*a__ ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(a__ ) , a__ , use_reentrant=a__ ) # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , a__ , use_reentrant=a__ ) else: for down_block in self.down_blocks: snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(a__ ) , a__ ) # middle snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , a__ ) else: # down for down_block in self.down_blocks: snake_case_ = down_block(a__ ) # middle snake_case_ = self.mid_block(a__ ) # post-process snake_case_ = self.conv_norm_out(a__ ) snake_case_ = self.conv_act(a__ ) snake_case_ = self.conv_out(a__ ) return sample class _snake_case ( nn.Module ): def __init__( self , a__=3 , a__=3 , a__=("UpDecoderBlock2D",) , a__=(64,) , a__=2 , a__=32 , a__="silu" , a__="group" , ) -> int: '''simple docstring''' super().__init__() snake_case_ = layers_per_block snake_case_ = nn.Convad( a__ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case_ = None snake_case_ = nn.ModuleList([] ) snake_case_ = in_channels if norm_type == "spatial" else None # mid snake_case_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=a__ , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=a__ , temb_channels=a__ , ) # up snake_case_ = list(reversed(a__ ) ) snake_case_ = reversed_block_out_channels[0] for i, up_block_type in enumerate(a__ ): snake_case_ = output_channel snake_case_ = reversed_block_out_channels[i] snake_case_ = i == len(a__ ) - 1 snake_case_ = get_up_block( a__ , num_layers=self.layers_per_block + 1 , in_channels=a__ , out_channels=a__ , prev_output_channel=a__ , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=a__ , resnet_groups=a__ , attention_head_dim=a__ , temb_channels=a__ , resnet_time_scale_shift=a__ , ) self.up_blocks.append(a__ ) snake_case_ = output_channel # out if norm_type == "spatial": snake_case_ = SpatialNorm(block_out_channels[0] , a__ ) else: snake_case_ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=a__ , eps=1e-6 ) snake_case_ = nn.SiLU() snake_case_ = nn.Convad(block_out_channels[0] , a__ , 3 , padding=1 ) snake_case_ = False def lowerCAmelCase__ ( self , a__ , a__=None ) -> Union[str, Any]: '''simple docstring''' snake_case_ = z snake_case_ = self.conv_in(a__ ) snake_case_ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(a__ ): def custom_forward(*a__ ): return module(*a__ ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , a__ , a__ , use_reentrant=a__ ) snake_case_ = sample.to(a__ ) # up for up_block in self.up_blocks: snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(a__ ) , a__ , a__ , use_reentrant=a__ ) else: # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , a__ , a__ ) snake_case_ = sample.to(a__ ) # up for up_block in self.up_blocks: snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(a__ ) , a__ , a__ ) else: # middle snake_case_ = self.mid_block(a__ , a__ ) snake_case_ = sample.to(a__ ) # up for up_block in self.up_blocks: snake_case_ = up_block(a__ , a__ ) # post-process if latent_embeds is None: snake_case_ = self.conv_norm_out(a__ ) else: snake_case_ = self.conv_norm_out(a__ , a__ ) snake_case_ = self.conv_act(a__ ) snake_case_ = self.conv_out(a__ ) return sample class _snake_case ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__=None , a__="random" , a__=False , a__=True ) -> Optional[Any]: '''simple docstring''' super().__init__() snake_case_ = n_e snake_case_ = vq_embed_dim snake_case_ = beta snake_case_ = legacy snake_case_ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case_ = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) snake_case_ = self.used.shape[0] snake_case_ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case_ = self.re_embed snake_case_ = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: snake_case_ = n_e snake_case_ = sane_index_shape def lowerCAmelCase__ ( self , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = inds.shape assert len(a__ ) > 1 snake_case_ = inds.reshape(ishape[0] , -1 ) snake_case_ = self.used.to(a__ ) snake_case_ = (inds[:, :, None] == used[None, None, ...]).long() snake_case_ = match.argmax(-1 ) snake_case_ = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case_ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case_ = self.unknown_index return new.reshape(a__ ) def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' snake_case_ = inds.shape assert len(a__ ) > 1 snake_case_ = inds.reshape(ishape[0] , -1 ) snake_case_ = self.used.to(a__ ) if self.re_embed > self.used.shape[0]: # extra token snake_case_ = 0 # simply set to zero snake_case_ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , a__ ) return back.reshape(a__ ) def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' snake_case_ = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case_ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case_ = torch.argmin(torch.cdist(a__ , self.embedding.weight ) , dim=1 ) snake_case_ = self.embedding(a__ ).view(z.shape ) snake_case_ = None snake_case_ = None # compute loss for embedding if not self.legacy: snake_case_ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case_ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case_ = z + (z_q - z).detach() # reshape back to match original input shape snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case_ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case_ = self.remap_to_used(a__ ) snake_case_ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case_ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def lowerCAmelCase__ ( self , a__ , a__ ) -> List[str]: '''simple docstring''' if self.remap is not None: snake_case_ = indices.reshape(shape[0] , -1 ) # add batch axis snake_case_ = self.unmap_to_all(a__ ) snake_case_ = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case_ = self.embedding(a__ ) if shape is not None: snake_case_ = z_q.view(a__ ) # reshape back to match original input shape snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class _snake_case ( lowercase_ ): def __init__( self , a__ , a__=False ) -> Optional[int]: '''simple docstring''' snake_case_ = parameters snake_case_ , snake_case_ = torch.chunk(a__ , 2 , dim=1 ) snake_case_ = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) snake_case_ = deterministic snake_case_ = torch.exp(0.5 * self.logvar ) snake_case_ = torch.exp(self.logvar ) if self.deterministic: snake_case_ = snake_case_ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def lowerCAmelCase__ ( self , a__ = None ) -> torch.FloatTensor: '''simple docstring''' snake_case_ = randn_tensor( self.mean.shape , generator=a__ , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case_ = self.mean + self.std * sample return x def lowerCAmelCase__ ( self , a__=None ) -> List[str]: '''simple docstring''' if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def lowerCAmelCase__ ( self , a__ , a__=[1, 2, 3] ) -> Optional[int]: '''simple docstring''' if self.deterministic: return torch.Tensor([0.0] ) snake_case_ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' return self.mean
400
0
# Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> List[str]: """simple docstring""" A__ = { '''en''': '''Machine learning is great, isn\'t it?''', '''ru''': '''Машинное обучение - это здорово, не так ли?''', '''de''': '''Maschinelles Lernen ist großartig, nicht wahr?''', } # BLUE scores as follows: # "pair": [fairseq, transformers] A__ = { '''wmt16-en-de-dist-12-1''': [28.3, 27.52], '''wmt16-en-de-dist-6-1''': [27.4, 27.11], '''wmt16-en-de-12-1''': [26.9, 25.75], } A__ = f"""{src_lang}-{tgt_lang}""" A__ = f""" --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt16 - allenai license: apache-2.0 datasets: - wmt16 metrics: - bleu --- # FSMT ## Model description This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}. For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369). All 3 models are available: * [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1) * [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1) * [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = \"allenai/{model_name}\" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = \"{texts[src_lang]}\" input_ids = tokenizer.encode(input, return_tensors=\"pt\") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias ## Training data Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369). ## Eval results Here are the BLEU scores: model | fairseq | transformers -------|---------|---------- {model_name} | {scores[model_name][0]} | {scores[model_name][1]} The score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs. The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=5 mkdir -p $DATA_DIR sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` ## Data Sources - [training, etc.](http://www.statmt.org/wmt16/) - [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372) ### BibTeX entry and citation info ``` @misc{{kasai2020deep, title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}}, author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}}, year={{2020}}, eprint={{2006.10369}}, archivePrefix={{arXiv}}, primaryClass={{cs.CL}} }} ``` """ model_card_dir.mkdir(parents=lowercase_ , exist_ok=lowercase_ ) A__ = os.path.join(lowercase_ , '''README.md''' ) print(f"""Generating {path}""" ) with open(lowercase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(lowercase_ ) # make sure we are under the root of the project _lowerCamelCase : Tuple = Path(__file__).resolve().parent.parent.parent _lowerCamelCase : int = repo_dir / """model_cards""" for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: _lowerCamelCase : str = model_cards_dir / """allenai""" / model_name write_model_card(model_card_dir, src_lang="""en""", tgt_lang="""de""", model_name=model_name)
177
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Dict: '''simple docstring''' A__ = 1 A__ = 3 A__ = (32, 32) A__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0)).to(UpperCAmelCase__) return image @property def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' torch.manual_seed(0) A__ = UNetaDConditionModel( block_out_channels=(32, 32, 64) , layers_per_block=2 , sample_size=32 , in_channels=7 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=8 , use_linear_projection=UpperCAmelCase__ , only_cross_attention=(True, True, False) , num_class_embeds=100 , ) return model @property def SCREAMING_SNAKE_CASE ( self : str) ->Dict: '''simple docstring''' torch.manual_seed(0) A__ = AutoencoderKL( block_out_channels=[32, 32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) return model @property def SCREAMING_SNAKE_CASE ( self : List[str]) ->Dict: '''simple docstring''' torch.manual_seed(0) A__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act='''gelu''' , projection_dim=512 , ) return CLIPTextModel(UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Tuple: '''simple docstring''' A__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator A__ = self.dummy_cond_unet_upscale A__ = DDPMScheduler() A__ = DDIMScheduler(prediction_type='''v_prediction''') A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') A__ = self.dummy_image.cpu().permute(0 , 2 , 3 , 1)[0] A__ = Image.fromarray(np.uinta(UpperCAmelCase__)).convert('''RGB''').resize((64, 64)) # make sure here that pndm scheduler skips prk A__ = StableDiffusionUpscalePipeline( unet=UpperCAmelCase__ , low_res_scheduler=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , max_noise_level=350 , ) A__ = sd_pipe.to(UpperCAmelCase__) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__) A__ = '''A painting of a squirrel eating a burger''' A__ = torch.Generator(device=UpperCAmelCase__).manual_seed(0) A__ = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , ) A__ = output.images A__ = torch.Generator(device=UpperCAmelCase__).manual_seed(0) A__ = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , return_dict=UpperCAmelCase__ , )[0] A__ = image[0, -3:, -3:, -1] A__ = image_from_tuple[0, -3:, -3:, -1] A__ = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) A__ = np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->int: '''simple docstring''' A__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator A__ = self.dummy_cond_unet_upscale A__ = DDPMScheduler() A__ = DDIMScheduler(prediction_type='''v_prediction''') A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') A__ = self.dummy_image.cpu().permute(0 , 2 , 3 , 1)[0] A__ = Image.fromarray(np.uinta(UpperCAmelCase__)).convert('''RGB''').resize((64, 64)) # make sure here that pndm scheduler skips prk A__ = StableDiffusionUpscalePipeline( unet=UpperCAmelCase__ , low_res_scheduler=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , max_noise_level=350 , ) A__ = sd_pipe.to(UpperCAmelCase__) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__) A__ = '''A painting of a squirrel eating a burger''' A__ = sd_pipe( 2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , ) A__ = output.images assert image.shape[0] == 2 A__ = torch.Generator(device=UpperCAmelCase__).manual_seed(0) A__ = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , ) A__ = output.images assert image.shape[0] == 2 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''') def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' A__ = self.dummy_cond_unet_upscale A__ = DDPMScheduler() A__ = DDIMScheduler(prediction_type='''v_prediction''') A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') A__ = self.dummy_image.cpu().permute(0 , 2 , 3 , 1)[0] A__ = Image.fromarray(np.uinta(UpperCAmelCase__)).convert('''RGB''').resize((64, 64)) # put models in fp16, except vae as it overflows in fp16 A__ = unet.half() A__ = text_encoder.half() # make sure here that pndm scheduler skips prk A__ = StableDiffusionUpscalePipeline( unet=UpperCAmelCase__ , low_res_scheduler=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , max_noise_level=350 , ) A__ = sd_pipe.to(UpperCAmelCase__) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__) A__ = '''A painting of a squirrel eating a burger''' A__ = torch.manual_seed(0) A__ = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=2 , output_type='''np''' , ).images A__ = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE ( self : Dict) ->str: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : str) ->Any: '''simple docstring''' A__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-upscale/low_res_cat.png''') A__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale''' '''/upsampled_cat.npy''') A__ = '''stabilityai/stable-diffusion-x4-upscaler''' A__ = StableDiffusionUpscalePipeline.from_pretrained(UpperCAmelCase__) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) pipe.enable_attention_slicing() A__ = '''a cat sitting on a park bench''' A__ = torch.manual_seed(0) A__ = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , output_type='''np''' , ) A__ = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image).max() < 1e-3 def SCREAMING_SNAKE_CASE ( self : int) ->str: '''simple docstring''' A__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-upscale/low_res_cat.png''') A__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale''' '''/upsampled_cat_fp16.npy''') A__ = '''stabilityai/stable-diffusion-x4-upscaler''' A__ = StableDiffusionUpscalePipeline.from_pretrained( UpperCAmelCase__ , torch_dtype=torch.floataa , ) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) pipe.enable_attention_slicing() A__ = '''a cat sitting on a park bench''' A__ = torch.manual_seed(0) A__ = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , output_type='''np''' , ) A__ = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image).max() < 5e-1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[Any]: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() A__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-upscale/low_res_cat.png''') A__ = '''stabilityai/stable-diffusion-x4-upscaler''' A__ = StableDiffusionUpscalePipeline.from_pretrained( UpperCAmelCase__ , torch_dtype=torch.floataa , ) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) pipe.enable_attention_slicing(1) pipe.enable_sequential_cpu_offload() A__ = '''a cat sitting on a park bench''' A__ = torch.manual_seed(0) A__ = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=5 , output_type='''np''' , ) A__ = torch.cuda.max_memory_allocated() # make sure that less than 2.9 GB is allocated assert mem_bytes < 2.9 * 10**9
177
1
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str=1_3 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : Dict=2_4 , UpperCAmelCase__ : Optional[int]=1_6 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[Any]=3_2 , UpperCAmelCase__ : str=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : str=3_7 , UpperCAmelCase__ : str="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[Any]=1_0 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Optional[Any]=2 , ) -> str: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = num_mel_bins __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __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 = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = frequency_stride __SCREAMING_SNAKE_CASE = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __SCREAMING_SNAKE_CASE = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 __SCREAMING_SNAKE_CASE = (self.max_length - self.patch_size) // self.time_stride + 1 __SCREAMING_SNAKE_CASE = frequency_out_dimension * time_out_dimension __SCREAMING_SNAKE_CASE = num_patches + 2 def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_values, labels def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple ) -> Any: __SCREAMING_SNAKE_CASE = ASTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_values": input_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case__ : List[Any] = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) snake_case__ : Optional[int] = False snake_case__ : List[str] = False snake_case__ : str = False snake_case__ : List[str] = False def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] ) -> Optional[int]: if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = ASTModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="AST does not use inputs_embeds" ) def UpperCAmelCase_ ( self : List[str] ) -> int: pass def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["input_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Dict ) -> str: for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = ASTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = torchaudio.load(lowerCAmelCase_ ) return audio, sampling_rate @require_torch @require_torchaudio class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : List[str] ) -> int: return ( ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ) if is_torchaudio_available() else None ) @slow def UpperCAmelCase_ ( self : str ) -> Tuple: __SCREAMING_SNAKE_CASE = self.default_feature_extractor __SCREAMING_SNAKE_CASE = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.default_feature_extractor __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = prepare_audio() __SCREAMING_SNAKE_CASE = audio.squeeze().numpy() __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , return_tensors="pt" ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) 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 : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) 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[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , 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[Any] ) -> str: 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 : List[Any] ) -> List[str]: 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 : List[str] ) -> Tuple: 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 : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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 : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = (EulerDiscreteScheduler,) _SCREAMING_SNAKE_CASE :Tuple = 10 def _a ( self , **_a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = { """num_train_timesteps""": 1_100, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", } config.update(**_a ) return config def _a ( self ) -> Optional[int]: """simple docstring""" for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def _a ( self ) -> List[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : str = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : int = self.dummy_model() SCREAMING_SNAKE_CASE__ : Dict = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[Any] = sample.to(_a ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : List[str] = scheduler.scale_model_input(_a , _a ) SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = scheduler.step(_a , _a , _a , generator=_a ) SCREAMING_SNAKE_CASE__ : str = output.prev_sample SCREAMING_SNAKE_CASE__ : List[str] = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 10.0_807 ) < 1E-2 assert abs(result_mean.item() - 0.0_131 ) < 1E-3 def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_scheduler_config(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : int = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_model() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Tuple = sample.to(_a ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Tuple = scheduler.scale_model_input(_a , _a ) SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step(_a , _a , _a , generator=_a ) SCREAMING_SNAKE_CASE__ : List[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[int] = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 0.0_002 ) < 1E-2 assert abs(result_mean.item() - 2.2_6_7_6E-0_6 ) < 1E-3 def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Tuple = scheduler_class(**_a ) scheduler.set_timesteps(self.num_inference_steps , device=_a ) SCREAMING_SNAKE_CASE__ : Dict = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = self.dummy_model() SCREAMING_SNAKE_CASE__ : int = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() SCREAMING_SNAKE_CASE__ : Dict = sample.to(_a ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : str = scheduler.scale_model_input(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , _a ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(_a , _a , _a , generator=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Dict = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Tuple = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 10.0_807 ) < 1E-2 assert abs(result_mean.item() - 0.0_131 ) < 1E-3 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[Any] = scheduler_class(**_a , use_karras_sigmas=_a ) scheduler.set_timesteps(self.num_inference_steps , device=_a ) SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() SCREAMING_SNAKE_CASE__ : Optional[int] = sample.to(_a ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.scale_model_input(_a , _a ) SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) SCREAMING_SNAKE_CASE__ : int = scheduler.step(_a , _a , _a , generator=_a ) SCREAMING_SNAKE_CASE__ : List[str] = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[int] = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Dict = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1E-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1E-3
711
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: a :List[Any] = None a :Optional[int] = logging.get_logger(__name__) a :Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} a :Optional[int] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } a :Dict = { "xlnet-base-cased": None, "xlnet-large-cased": None, } a :int = "▁" # Segments (not really needed) a :Dict = 0 a :Optional[int] = 1 a :Tuple = 2 a :List[str] = 3 a :Optional[Any] = 4 class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = """left""" _SCREAMING_SNAKE_CASE :Optional[Any] = XLNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , **_a , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE__ : List[str] = remove_space SCREAMING_SNAKE_CASE__ : int = keep_accents SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_file SCREAMING_SNAKE_CASE__ : Tuple = False if not self.vocab_file else True def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _lowercase ( self : Tuple ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) __magic_name__ = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def _lowercase ( self : int ) -> List[Any]: """simple docstring""" __magic_name__ = self.dummy_uncond_unet __magic_name__ = KarrasVeScheduler() __magic_name__ = KarrasVePipeline(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe(num_inference_steps=2 , generator=UpperCamelCase__ , output_type="""numpy""" ).images __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe(num_inference_steps=2 , generator=UpperCamelCase__ , output_type="""numpy""" , return_dict=UpperCamelCase__ )[0] __magic_name__ = image[0, -3:, -3:, -1] __magic_name__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __magic_name__ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = """google/ncsnpp-celebahq-256""" __magic_name__ = UNetaDModel.from_pretrained(UpperCamelCase__ ) __magic_name__ = KarrasVeScheduler() __magic_name__ = KarrasVePipeline(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe(num_inference_steps=20 , generator=UpperCamelCase__ , output_type="""numpy""" ).images __magic_name__ = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __magic_name__ = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
529
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available __lowerCAmelCase : Dict = logging.getLogger(__name__) @dataclass class UpperCAmelCase_ : '''simple docstring''' a__ = 42 a__ = 42 a__ = 42 @dataclass class UpperCAmelCase_ : '''simple docstring''' a__ = 42 a__ = 42 a__ = None a__ = None class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """train""" a__ = """dev""" a__ = """test""" class UpperCAmelCase_ : '''simple docstring''' @staticmethod def _lowercase ( UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[Split, str] ) -> List[InputExample]: """simple docstring""" raise NotImplementedError @staticmethod def _lowercase ( UpperCamelCase__ : str ) -> List[str]: """simple docstring""" raise NotImplementedError @staticmethod def _lowercase ( UpperCamelCase__ : List[InputExample] , UpperCamelCase__ : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : PreTrainedTokenizer , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Tuple="[CLS]" , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : str="[SEP]" , UpperCamelCase__ : int=False , UpperCamelCase__ : Dict=False , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : str=0 , UpperCamelCase__ : Optional[Any]=-100 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : Optional[int]=True , ) -> List[InputFeatures]: """simple docstring""" __magic_name__ = {label: i for i, label in enumerate(UpperCamelCase__ )} __magic_name__ = [] for ex_index, example in enumerate(UpperCamelCase__ ): if ex_index % 1_0000 == 0: logger.info("""Writing example %d of %d""" , UpperCamelCase__ , len(UpperCamelCase__ ) ) __magic_name__ = [] __magic_name__ = [] for word, label in zip(example.words , example.labels ): __magic_name__ = tokenizer.tokenize(UpperCamelCase__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(UpperCamelCase__ ) > 0: tokens.extend(UpperCamelCase__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(UpperCamelCase__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __magic_name__ = tokenizer.num_special_tokens_to_add() if len(UpperCamelCase__ ) > max_seq_length - special_tokens_count: __magic_name__ = tokens[: (max_seq_length - special_tokens_count)] __magic_name__ = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __magic_name__ = [sequence_a_segment_id] * len(UpperCamelCase__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __magic_name__ = [cls_token] + tokens __magic_name__ = [pad_token_label_id] + label_ids __magic_name__ = [cls_token_segment_id] + segment_ids __magic_name__ = tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __magic_name__ = [1 if mask_padding_with_zero else 0] * len(UpperCamelCase__ ) # Zero-pad up to the sequence length. __magic_name__ = max_seq_length - len(UpperCamelCase__ ) if pad_on_left: __magic_name__ = ([pad_token] * padding_length) + input_ids __magic_name__ = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __magic_name__ = ([pad_token_segment_id] * padding_length) + segment_ids __magic_name__ = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(UpperCamelCase__ ) == max_seq_length assert len(UpperCamelCase__ ) == max_seq_length assert len(UpperCamelCase__ ) == max_seq_length assert len(UpperCamelCase__ ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(UpperCamelCase__ ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(UpperCamelCase__ ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(UpperCamelCase__ ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(UpperCamelCase__ ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(UpperCamelCase__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __magic_name__ = None features.append( InputFeatures( input_ids=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , label_ids=UpperCamelCase__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = 42 a__ = nn.CrossEntropyLoss().ignore_index def __init__( self : Optional[Any] , UpperCamelCase__ : TokenClassificationTask , UpperCamelCase__ : str , UpperCamelCase__ : PreTrainedTokenizer , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Split = Split.train , ) -> str: """simple docstring""" __magic_name__ = os.path.join( UpperCamelCase__ , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(UpperCamelCase__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __magic_name__ = cached_features_file + """.lock""" with FileLock(UpperCamelCase__ ): if os.path.exists(UpperCamelCase__ ) and not overwrite_cache: logger.info(F'''Loading features from cached file {cached_features_file}''' ) __magic_name__ = torch.load(UpperCamelCase__ ) else: logger.info(F'''Creating features from dataset file at {data_dir}''' ) __magic_name__ = token_classification_task.read_examples_from_file(UpperCamelCase__ , UpperCamelCase__ ) # TODO clean up all this to leverage built-in features of tokenizers __magic_name__ = token_classification_task.convert_examples_to_features( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=UpperCamelCase__ , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , UpperCamelCase__ ) def __len__( self : List[str] ) -> Any: """simple docstring""" return len(self.features ) def __getitem__( self : Tuple , UpperCamelCase__ : Union[str, Any] ) -> InputFeatures: """simple docstring""" return self.features[i] if is_tf_available(): import tensorflow as tf class UpperCAmelCase_ : '''simple docstring''' a__ = 42 a__ = -1_00 def __init__( self : List[str] , UpperCamelCase__ : TokenClassificationTask , UpperCamelCase__ : str , UpperCamelCase__ : PreTrainedTokenizer , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : Split = Split.train , ) -> List[Any]: """simple docstring""" __magic_name__ = token_classification_task.read_examples_from_file(UpperCamelCase__ , UpperCamelCase__ ) # TODO clean up all this to leverage built-in features of tokenizers __magic_name__ = token_classification_task.convert_examples_to_features( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=UpperCamelCase__ , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __magic_name__ = tf.data.Dataset.from_generator( UpperCamelCase__ , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __magic_name__ = tf.data.Dataset.from_generator( UpperCamelCase__ , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def _lowercase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" __magic_name__ = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : Tuple ) -> Tuple: """simple docstring""" return len(self.features ) def __getitem__( self : Optional[Any] , UpperCamelCase__ : Union[str, Any] ) -> InputFeatures: """simple docstring""" return self.features[i]
529
1
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( A : Union[str, Any] , A : Any ): '''simple docstring''' if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
700
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase__( unittest.TestCase ): def __init__( self : Dict , lowerCAmelCase : List[str] , lowerCAmelCase : List[Any]=3 , lowerCAmelCase : Tuple=32 , lowerCAmelCase : Optional[int]=3 , lowerCAmelCase : Optional[Any]=10 , lowerCAmelCase : Optional[Any]=[10, 20, 30, 40] , lowerCAmelCase : Optional[int]=[1, 1, 2, 1] , lowerCAmelCase : Union[str, Any]=True , lowerCAmelCase : Tuple=True , lowerCAmelCase : List[Any]="relu" , lowerCAmelCase : List[Any]=3 , lowerCAmelCase : Union[str, Any]=None , )-> Optional[int]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = num_channels UpperCAmelCase = embeddings_size UpperCAmelCase = hidden_sizes UpperCAmelCase = depths UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_act UpperCAmelCase = num_labels UpperCAmelCase = scope UpperCAmelCase = len(lowerCAmelCase ) def a__( self : Optional[Any] )-> Tuple: """simple docstring""" UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = self.get_config() return config, pixel_values def a__( self : str )-> Optional[Any]: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def a__( self : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Any )-> Union[str, Any]: """simple docstring""" UpperCAmelCase = FlaxRegNetModel(config=lowerCAmelCase ) UpperCAmelCase = model(lowerCAmelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def a__( self : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Optional[Any] )-> List[str]: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = FlaxRegNetForImageClassification(config=lowerCAmelCase ) UpperCAmelCase = model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__( self : List[str] )-> Any: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCamelCase__( lowerCAmelCase , unittest.TestCase ): __magic_name__ : Optional[int] = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __magic_name__ : Optional[int] = False __magic_name__ : List[str] = False __magic_name__ : Dict = False def a__( self : Union[str, Any] )-> None: """simple docstring""" UpperCAmelCase = FlaxRegNetModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase ) def a__( self : List[str] )-> List[str]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def a__( self : Tuple )-> Tuple: """simple docstring""" return def a__( self : Optional[Any] )-> Tuple: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def a__( self : Any )-> Optional[int]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def a__( self : str )-> Optional[Any]: """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def a__( self : Any )-> List[str]: """simple docstring""" pass def a__( self : Any )-> Optional[Any]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(lowerCAmelCase ) UpperCAmelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def a__( self : Tuple )-> int: """simple docstring""" def check_hidden_states_output(lowerCAmelCase : Optional[Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : int ): UpperCAmelCase = model_class(lowerCAmelCase ) UpperCAmelCase = model(**self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) ) UpperCAmelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCAmelCase = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase ) , expected_num_stages + 1 ) UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase = True check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def a__( self : Union[str, Any] )-> List[str]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCAmelCase = self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase = model_class(lowerCAmelCase ) @jax.jit def model_jitted(lowerCAmelCase : Tuple , **lowerCAmelCase : Tuple ): return model(pixel_values=lowerCAmelCase , **lowerCAmelCase ) with self.subTest('''JIT Enabled''' ): UpperCAmelCase = model_jitted(**lowerCAmelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): UpperCAmelCase = model_jitted(**lowerCAmelCase ).to_tuple() self.assertEqual(len(lowerCAmelCase ) , len(lowerCAmelCase ) ) for jitted_output, output in zip(lowerCAmelCase , lowerCAmelCase ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( ): '''simple docstring''' UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCamelCase__( unittest.TestCase ): @cached_property def a__( self : Dict )-> int: """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def a__( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" UpperCAmelCase = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=lowerCAmelCase , return_tensors='''np''' ) UpperCAmelCase = model(**lowerCAmelCase ) # verify the logits UpperCAmelCase = (1, 1000) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) UpperCAmelCase = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) )
50
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() a = logging.get_logger(__name__) def _snake_case ( _snake_case : str ) -> YolosConfig: '''simple docstring''' _A = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _A = 1_92 _A = 7_68 _A = 12 _A = 3 _A = [8_00, 13_33] _A = False elif yolos_name == "yolos_s_dWr": _A = 3_30 _A = 14 _A = 6 _A = 13_20 elif "yolos_s" in yolos_name: _A = 3_84 _A = 15_36 _A = 12 _A = 6 elif "yolos_b" in yolos_name: _A = [8_00, 13_44] _A = 91 _A = 'huggingface/label-files' _A = 'coco-detection-id2label.json' _A = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type='dataset' ) , 'r' ) ) _A = {int(_snake_case ): v for k, v in idalabel.items()} _A = idalabel _A = {v: k for k, v in idalabel.items()} return config def _snake_case ( _snake_case : dict , _snake_case : YolosConfig , _snake_case : bool = False ) -> List[Any]: '''simple docstring''' for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _A = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) _A = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _A = in_proj_weight[: config.hidden_size, :] _A = in_proj_bias[: config.hidden_size] _A = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _A = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _A = in_proj_weight[-config.hidden_size :, :] _A = in_proj_bias[-config.hidden_size :] def _snake_case ( _snake_case : str ) -> str: '''simple docstring''' if "backbone" in name: _A = name.replace('backbone' , 'vit' ) if "cls_token" in name: _A = name.replace('cls_token' , 'embeddings.cls_token' ) if "det_token" in name: _A = name.replace('det_token' , 'embeddings.detection_tokens' ) if "mid_pos_embed" in name: _A = name.replace('mid_pos_embed' , 'encoder.mid_position_embeddings' ) if "pos_embed" in name: _A = name.replace('pos_embed' , 'embeddings.position_embeddings' ) if "patch_embed.proj" in name: _A = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "blocks" in name: _A = name.replace('blocks' , 'encoder.layer' ) if "attn.proj" in name: _A = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: _A = name.replace('attn' , 'attention.self' ) if "norm1" in name: _A = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: _A = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: _A = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: _A = name.replace('mlp.fc2' , 'output.dense' ) if "class_embed" in name: _A = name.replace('class_embed' , 'class_labels_classifier' ) if "bbox_embed" in name: _A = name.replace('bbox_embed' , 'bbox_predictor' ) if "vit.norm" in name: _A = name.replace('vit.norm' , 'vit.layernorm' ) return name def _snake_case ( _snake_case : dict , _snake_case : YolosForObjectDetection ) -> dict: '''simple docstring''' for key in orig_state_dict.copy().keys(): _A = orig_state_dict.pop(_snake_case ) if "qkv" in key: _A = key.split('.' ) _A = int(key_split[2] ) _A = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _A = val[:dim, :] _A = val[ dim : dim * 2, : ] _A = val[-dim:, :] else: _A = val[:dim] _A = val[dim : dim * 2] _A = val[-dim:] else: _A = val return orig_state_dict def _snake_case ( ) -> torch.Tensor: '''simple docstring''' _A = 'http://images.cocodataset.org/val2017/000000039769.jpg' _A = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ) return im @torch.no_grad() def _snake_case ( _snake_case : str , _snake_case : str , _snake_case : str , _snake_case : bool = False ) -> Union[str, Any]: '''simple docstring''' _A = get_yolos_config(_snake_case ) # load original state_dict _A = torch.load(_snake_case , map_location='cpu' )['model'] # load 🤗 model _A = YolosForObjectDetection(_snake_case ) model.eval() _A = convert_state_dict(_snake_case , _snake_case ) model.load_state_dict(_snake_case ) # Check outputs on an image, prepared by YolosImageProcessor _A = 8_00 if yolos_name != 'yolos_ti' else 5_12 _A = YolosImageProcessor(format='coco_detection' , size=_snake_case ) _A = image_processor(images=prepare_img() , return_tensors='pt' ) _A = model(**_snake_case ) _A , _A = outputs.logits, outputs.pred_boxes _A , _A = None, None if yolos_name == "yolos_ti": _A = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) _A = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": _A = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) _A = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": _A = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) _A = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": _A = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) _A = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": _A = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) _A = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(F'''Unknown yolos_name: {yolos_name}''' ) assert torch.allclose(logits[0, :3, :3] , _snake_case , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , _snake_case , atol=1E-4 ) Path(_snake_case ).mkdir(exist_ok=_snake_case ) print(F'''Saving model {yolos_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_snake_case ) if push_to_hub: _A = { 'yolos_ti': 'yolos-tiny', 'yolos_s_200_pre': 'yolos-small', 'yolos_s_300_pre': 'yolos-small-300', 'yolos_s_dWr': 'yolos-small-dwr', 'yolos_base': 'yolos-base', } print('Pushing to the hub...' ) _A = model_mapping[yolos_name] image_processor.push_to_hub(_snake_case , organization='hustvl' ) model.push_to_hub(_snake_case , organization='hustvl' ) if __name__ == "__main__": a = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.pth file).''' ) 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.''' ) a = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
7
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def snake_case ( ) -> Generator[int, None, None]: lowerCamelCase : dict[int, int] = {} lowerCamelCase : str = 2 while True: lowerCamelCase : int = factor_map.pop(UpperCamelCase__ , UpperCamelCase__ ) if factor: lowerCamelCase : List[Any] = factor + prime while x in factor_map: x += factor lowerCamelCase : int = factor else: lowerCamelCase : Optional[int] = prime yield prime prime += 1 def snake_case ( UpperCamelCase__ : float = 1E10 ) -> int: lowerCamelCase : Optional[int] = sieve() lowerCamelCase : List[str] = 1 while True: lowerCamelCase : Tuple = next(UpperCamelCase__ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(UpperCamelCase__ ) n += 2 if __name__ == "__main__": print(solution())
222
0
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input("Enter image url: ").strip() print(F'''Downloading image from {url} ...''') lowercase_ = BeautifulSoup(requests.get(url).content, "html.parser") # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find("meta", {"property": "og:image"})["content"] lowercase_ = requests.get(image_url).content lowercase_ = F'''{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg''' with open(file_name, "wb") as fp: fp.write(image_data) print(F'''Done. Image saved to disk as {file_name}.''')
390
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 lowercase_ = get_tests_dir("fixtures/dummy_feature_extractor_config.json") lowercase_ = get_tests_dir("fixtures/vocab.json") lowercase_ = get_tests_dir("fixtures") class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): A : str = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] def snake_case__ ( self : Union[str, Any] ): __snake_case : int = 0 def snake_case__ ( self : int ): __snake_case : List[Any] = AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : Union[str, Any] = WavaVecaConfig() __snake_case : Union[str, Any] = AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) # save in new folder model_config.save_pretrained(_lowerCAmelCase ) processor.save_pretrained(_lowerCAmelCase ) __snake_case : Optional[Any] = AutoProcessor.from_pretrained(_lowerCAmelCase ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(_lowerCAmelCase , os.path.join(_lowerCAmelCase , _lowerCAmelCase ) ) copyfile(_lowerCAmelCase , os.path.join(_lowerCAmelCase , """vocab.json""" ) ) __snake_case : str = AutoProcessor.from_pretrained(_lowerCAmelCase ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Dict ): with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : Tuple = WavaVecaFeatureExtractor() __snake_case : Optional[int] = AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) __snake_case : int = WavaVecaProcessor(_lowerCAmelCase , _lowerCAmelCase ) # save in new folder processor.save_pretrained(_lowerCAmelCase ) # drop `processor_class` in tokenizer with open(os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , """r""" ) as f: __snake_case : Any = json.load(_lowerCAmelCase ) config_dict.pop("""processor_class""" ) with open(os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , """w""" ) as f: f.write(json.dumps(_lowerCAmelCase ) ) __snake_case : Optional[Any] = AutoProcessor.from_pretrained(_lowerCAmelCase ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Union[str, Any] ): with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : List[Any] = WavaVecaFeatureExtractor() __snake_case : Dict = AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) __snake_case : Any = WavaVecaProcessor(_lowerCAmelCase , _lowerCAmelCase ) # save in new folder processor.save_pretrained(_lowerCAmelCase ) # drop `processor_class` in feature extractor with open(os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , """r""" ) as f: __snake_case : List[Any] = json.load(_lowerCAmelCase ) config_dict.pop("""processor_class""" ) with open(os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , """w""" ) as f: f.write(json.dumps(_lowerCAmelCase ) ) __snake_case : List[Any] = AutoProcessor.from_pretrained(_lowerCAmelCase ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Any ): with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : List[Any] = WavaVecaConfig(processor_class="""Wav2Vec2Processor""" ) model_config.save_pretrained(_lowerCAmelCase ) # copy relevant files copyfile(_lowerCAmelCase , os.path.join(_lowerCAmelCase , """vocab.json""" ) ) # create emtpy sample processor with open(os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , """w""" ) as f: f.write("""{}""" ) __snake_case : int = AutoProcessor.from_pretrained(_lowerCAmelCase ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( self : Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCAmelCase ): __snake_case : List[Any] = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCAmelCase ): __snake_case : Any = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=_lowerCAmelCase ) __snake_case : int = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" , trust_remote_code=_lowerCAmelCase ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) __snake_case : List[str] = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) __snake_case : Dict = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version __snake_case : str = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=_lowerCAmelCase , use_fast=_lowerCAmelCase ) __snake_case : Optional[Any] = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def snake_case__ ( self : Union[str, Any] ): try: AutoConfig.register("""custom""" , _lowerCAmelCase ) AutoFeatureExtractor.register(_lowerCAmelCase , _lowerCAmelCase ) AutoTokenizer.register(_lowerCAmelCase , slow_tokenizer_class=_lowerCAmelCase ) AutoProcessor.register(_lowerCAmelCase , _lowerCAmelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCAmelCase ): AutoProcessor.register(_lowerCAmelCase , _lowerCAmelCase ) # Now that the config is registered, it can be used as any other config with the auto-API __snake_case : List[str] = CustomFeatureExtractor.from_pretrained(_lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : Dict = os.path.join(_lowerCAmelCase , """vocab.txt""" ) with open(_lowerCAmelCase , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) __snake_case : Optional[int] = CustomTokenizer(_lowerCAmelCase ) __snake_case : Any = CustomProcessor(_lowerCAmelCase , _lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(_lowerCAmelCase ) __snake_case : Dict = AutoProcessor.from_pretrained(_lowerCAmelCase ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def snake_case__ ( self : Dict ): class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): A : Optional[Any] = False class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): A : List[Any] = False class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): A : Optional[int] = "AutoFeatureExtractor" A : List[Any] = "AutoTokenizer" A : Union[str, Any] = False try: AutoConfig.register("""custom""" , _lowerCAmelCase ) AutoFeatureExtractor.register(_lowerCAmelCase , _lowerCAmelCase ) AutoTokenizer.register(_lowerCAmelCase , slow_tokenizer_class=_lowerCAmelCase ) AutoProcessor.register(_lowerCAmelCase , _lowerCAmelCase ) # If remote code is not set, the default is to use local classes. __snake_case : Any = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. __snake_case : List[Any] = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=_lowerCAmelCase ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. __snake_case : Dict = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=_lowerCAmelCase ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def snake_case__ ( self : str ): __snake_case : str = AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(processor.__class__.__name__ , """BertTokenizerFast""" ) def snake_case__ ( self : List[Any] ): __snake_case : Optional[Any] = AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-convnext""" ) self.assertEqual(processor.__class__.__name__ , """ConvNextImageProcessor""" ) @is_staging_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): A : Union[str, Any] = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def snake_case__ ( cls : Optional[Any] ): __snake_case : List[Any] = TOKEN HfFolder.save_token(_lowerCAmelCase ) @classmethod def snake_case__ ( cls : Optional[int] ): try: delete_repo(token=cls._token , repo_id="""test-processor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-processor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-processor""" ) except HTTPError: pass def snake_case__ ( self : Dict ): __snake_case : str = WavaVecaProcessor.from_pretrained(_lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(_lowerCAmelCase , """test-processor""" ) , push_to_hub=_lowerCAmelCase , use_auth_token=self._token ) __snake_case : Optional[Any] = WavaVecaProcessor.from_pretrained(f'''{USER}/test-processor''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(_lowerCAmelCase , getattr(new_processor.feature_extractor , _lowerCAmelCase ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def snake_case__ ( self : List[str] ): __snake_case : Dict = WavaVecaProcessor.from_pretrained(_lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(_lowerCAmelCase , """test-processor-org""" ) , push_to_hub=_lowerCAmelCase , use_auth_token=self._token , organization="""valid_org""" , ) __snake_case : List[str] = WavaVecaProcessor.from_pretrained("""valid_org/test-processor-org""" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(_lowerCAmelCase , getattr(new_processor.feature_extractor , _lowerCAmelCase ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def snake_case__ ( self : List[str] ): CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() __snake_case : Optional[Any] = CustomFeatureExtractor.from_pretrained(_lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : List[Any] = os.path.join(_lowerCAmelCase , """vocab.txt""" ) with open(_lowerCAmelCase , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) __snake_case : Dict = CustomTokenizer(_lowerCAmelCase ) __snake_case : List[Any] = CustomProcessor(_lowerCAmelCase , _lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(f'''{USER}/test-dynamic-processor''' , token=self._token ) __snake_case : str = Repository(_lowerCAmelCase , clone_from=f'''{USER}/test-dynamic-processor''' , token=self._token ) processor.save_pretrained(_lowerCAmelCase ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { """AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor""", """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(_lowerCAmelCase , """tokenizer_config.json""" ) ) as f: __snake_case : int = json.load(_lowerCAmelCase ) self.assertDictEqual( tokenizer_config["""auto_map"""] , { """AutoTokenizer""": ["""custom_tokenization.CustomTokenizer""", None], """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(_lowerCAmelCase , """custom_feature_extraction.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(_lowerCAmelCase , """custom_tokenization.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(_lowerCAmelCase , """custom_processing.py""" ) ) ) repo.push_to_hub() __snake_case : Any = AutoProcessor.from_pretrained(f'''{USER}/test-dynamic-processor''' , trust_remote_code=_lowerCAmelCase ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , """CustomProcessor""" )
390
1
"""simple docstring""" import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( "The `image_to_image.py` script is outdated. Please use directly `from diffusers import" " StableDiffusionImg2ImgPipeline` instead." )
391
"""simple docstring""" import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging __A : Tuple = { '''cola''': 2, '''mnli''': 3, '''mrpc''': 2, '''sst-2''': 2, '''sts-b''': 1, '''qqp''': 2, '''qnli''': 2, '''rte''': 2, '''wnli''': 2, } logging.set_verbosity_info() def lowercase ( __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Optional[Any] , __snake_case : str=None ): # Initialise PyTorch model lowercase_ : List[Any] = XLNetConfig.from_json_file(__snake_case ) lowercase_ : Any = finetuning_task.lower() if finetuning_task is not None else '''''' if finetuning_task in GLUE_TASKS_NUM_LABELS: print(F'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) lowercase_ : Optional[Any] = finetuning_task lowercase_ : Optional[int] = GLUE_TASKS_NUM_LABELS[finetuning_task] lowercase_ : List[str] = XLNetForSequenceClassification(__snake_case ) elif "squad" in finetuning_task: lowercase_ : Dict = finetuning_task lowercase_ : List[str] = XLNetForQuestionAnswering(__snake_case ) else: lowercase_ : Union[str, Any] = XLNetLMHeadModel(__snake_case ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(__snake_case , __snake_case , __snake_case ) # Save pytorch-model lowercase_ : Tuple = os.path.join(__snake_case , __snake_case ) lowercase_ : Tuple = os.path.join(__snake_case , __snake_case ) print(F'''Save PyTorch model to {os.path.abspath(__snake_case )}''' ) torch.save(model.state_dict() , __snake_case ) print(F'''Save configuration file to {os.path.abspath(__snake_case )}''' ) with open(__snake_case , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--xlnet_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained XLNet model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the folder to store the PyTorch model or dataset/vocab.''', ) parser.add_argument( '''--finetuning_task''', default=None, type=str, help='''Name of a task on which the XLNet TensorFlow model was fine-tuned''', ) __A : int = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
231
0
"""simple docstring""" import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup _UpperCamelCase : Tuple = logging.get_logger(__name__) class snake_case ( UpperCAmelCase ): def __init__( self : Optional[int] , **A : str ): '''simple docstring''' requires_backends(self , ['bs4'] ) super().__init__(**A ) def lowerCamelCase__ ( self : Optional[int] , A : Optional[Any] ): '''simple docstring''' a : Union[str, Any] = [] a : str = [] a : List[Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag a : Optional[Any] = 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 ) ) a : str = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def lowerCamelCase__ ( self : str , A : int ): '''simple docstring''' a : Optional[int] = BeautifulSoup(A , 'html.parser' ) a : Dict = [] a : Tuple = [] a : Dict = [] for element in html_code.descendants: if type(A ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue a : Union[str, Any] = html.unescape(A ).strip() if not text_in_this_tag: continue all_doc_strings.append(A ) a, a : 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 lowerCamelCase__ ( self : List[Any] , A : str , A : Any ): '''simple docstring''' a : List[str] = '' for tagname, subs in zip(A , A ): xpath += F'''/{tagname}''' if subs != 0: xpath += F'''[{subs}]''' return xpath def __call__( self : Any , A : Optional[Any] ): '''simple docstring''' a : List[str] = False # Check that strings has a valid type if isinstance(A , A ): a : List[str] = True elif isinstance(A , (list, tuple) ): if len(A ) == 0 or isinstance(html_strings[0] , A ): a : int = 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 )}.''' ) a : List[str] = bool(isinstance(A , (list, tuple) ) and (isinstance(html_strings[0] , A )) ) if not is_batched: a : List[Any] = [html_strings] # Get nodes + xpaths a : int = [] a : Dict = [] for html_string in html_strings: a, a, a : List[Any] = self.get_three_from_single(A ) nodes.append(A ) a : str = [] for node, tag_list, sub_list in zip(A , A , A ): a : int = self.construct_xpath(A , A ) xpath_strings.append(A ) xpaths.append(A ) # return as Dict a : Optional[int] = {'nodes': nodes, 'xpaths': xpaths} a : Tuple = BatchFeature(data=A , tensor_type=A ) return encoded_inputs
118
"""simple docstring""" 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 snake_case : def __init__( self : Optional[int] , A : Optional[Any] , A : Tuple=1_3 , A : Optional[int]=7 , A : Tuple=True , A : Any=True , A : Union[str, Any]=True , A : Any=True , A : List[Any]=9_9 , A : Optional[int]=1_6 , A : Tuple=3_6 , A : str=6 , A : Tuple=6 , A : Optional[Any]=6 , A : Any=3_7 , A : int="gelu" , A : Optional[int]=0.1 , A : Dict=0.1 , A : Union[str, Any]=5_1_2 , A : int=1_6 , A : int=2 , A : Tuple=0.02 , A : Optional[Any]=3 , A : str=4 , A : Tuple=None , ): '''simple docstring''' a : int = parent a : List[str] = batch_size a : List[str] = seq_length a : int = is_training a : int = use_input_mask a : List[str] = use_token_type_ids a : int = use_labels a : int = vocab_size a : Any = embedding_size a : Any = hidden_size a : Any = num_hidden_layers a : List[Any] = num_hidden_groups a : Optional[int] = num_attention_heads a : str = intermediate_size a : str = hidden_act a : Dict = hidden_dropout_prob a : List[str] = attention_probs_dropout_prob a : int = max_position_embeddings a : Optional[int] = type_vocab_size a : int = type_sequence_label_size a : Tuple = initializer_range a : str = num_labels a : Union[str, Any] = num_choices a : Dict = scope def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : int = None if self.use_input_mask: a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : Union[str, Any] = None if self.use_token_type_ids: a : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a : List[str] = None a : Dict = None a : Dict = None if self.use_labels: a : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : int = ids_tensor([self.batch_size] , self.num_choices ) a : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : List[str] ): '''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 lowerCamelCase__ ( self : Optional[int] , A : Tuple , A : Optional[Any] , A : Optional[int] , A : Dict , A : List[str] , A : Optional[Any] , A : str ): '''simple docstring''' a : Dict = AlbertModel(config=A ) model.to(A ) model.eval() a : List[str] = model(A , attention_mask=A , token_type_ids=A ) a : str = model(A , token_type_ids=A ) a : 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 lowerCamelCase__ ( self : List[Any] , A : int , A : Any , A : List[str] , A : List[str] , A : Optional[int] , A : Tuple , A : Optional[int] ): '''simple docstring''' a : int = AlbertForPreTraining(config=A ) model.to(A ) model.eval() a : Dict = 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 lowerCamelCase__ ( self : int , A : Tuple , A : Any , A : Dict , A : Optional[int] , A : Dict , A : int , A : str ): '''simple docstring''' a : Optional[int] = AlbertForMaskedLM(config=A ) model.to(A ) model.eval() a : Optional[Any] = 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 lowerCamelCase__ ( self : int , A : Union[str, Any] , A : int , A : Dict , A : Tuple , A : str , A : List[Any] , A : str ): '''simple docstring''' a : Optional[int] = AlbertForQuestionAnswering(config=A ) model.to(A ) model.eval() a : 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 lowerCamelCase__ ( self : Tuple , A : List[Any] , A : List[str] , A : List[str] , A : Any , A : List[Any] , A : Dict , A : str ): '''simple docstring''' a : Optional[int] = self.num_labels a : Optional[Any] = AlbertForSequenceClassification(A ) model.to(A ) model.eval() a : str = model(A , attention_mask=A , token_type_ids=A , labels=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : Optional[Any] , A : List[Any] , A : Optional[int] , A : List[Any] , A : str , A : Dict , A : Optional[Any] , A : Any ): '''simple docstring''' a : Optional[int] = self.num_labels a : str = AlbertForTokenClassification(config=A ) model.to(A ) model.eval() a : List[str] = 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 lowerCamelCase__ ( self : Dict , A : Optional[int] , A : int , A : int , A : List[Any] , A : List[str] , A : Optional[Any] , A : str ): '''simple docstring''' a : List[str] = self.num_choices a : str = AlbertForMultipleChoice(config=A ) model.to(A ) model.eval() a : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a : str = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a : Union[str, 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 lowerCamelCase__ ( self : str ): '''simple docstring''' a : Tuple = self.prepare_config_and_inputs() ( ( a ), ( a ), ( a ), ( a ), ( a ), ( a ), ( a ), ) : Dict = config_and_inputs a : List[Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): __magic_name__ = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) __magic_name__ = ( { '''feature-extraction''': AlbertModel, '''fill-mask''': AlbertForMaskedLM, '''question-answering''': AlbertForQuestionAnswering, '''text-classification''': AlbertForSequenceClassification, '''token-classification''': AlbertForTokenClassification, '''zero-shot''': AlbertForSequenceClassification, } if is_torch_available() else {} ) __magic_name__ = True def lowerCamelCase__ ( self : Union[str, Any] , A : List[str] , A : Tuple , A : Tuple=False ): '''simple docstring''' a : List[Any] = super()._prepare_for_class(A , A , return_labels=A ) if return_labels: if model_class in get_values(A ): a : Union[str, Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=A ) a : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A ) return inputs_dict def lowerCamelCase__ ( self : Any ): '''simple docstring''' a : int = AlbertModelTester(self ) a : List[Any] = ConfigTester(self , config_class=A , hidden_size=3_7 ) def lowerCamelCase__ ( self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def lowerCamelCase__ ( self : int ): '''simple docstring''' a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*A ) def lowerCamelCase__ ( self : Dict ): '''simple docstring''' a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A ) def lowerCamelCase__ ( self : int ): '''simple docstring''' a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A ) def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) def lowerCamelCase__ ( self : int ): '''simple docstring''' a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def lowerCamelCase__ ( self : int ): '''simple docstring''' a : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a : Optional[Any] = type self.model_tester.create_and_check_model(*A ) @slow def lowerCamelCase__ ( self : Any ): '''simple docstring''' for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Tuple = AlbertModel.from_pretrained(A ) self.assertIsNotNone(A ) @require_torch class snake_case ( unittest.TestCase ): @slow def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' a : List[Any] = AlbertModel.from_pretrained('albert-base-v2' ) a : Union[str, Any] = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) a : str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): a : Optional[Any] = model(A , attention_mask=A )[0] a : List[Any] = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , A ) a : int = 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 ) )
118
1
'''simple docstring''' import sys from collections import defaultdict class a__ : def __init__( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = [] def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[str] ): """simple docstring""" return self.node_position[vertex] def SCREAMING_SNAKE_CASE__ ( self : int , a : Dict , a : Any ): """simple docstring""" __lowerCamelCase = pos def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : Tuple , a : str , a : Dict , a : Tuple ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCamelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCamelCase = 2 * start + 1 else: __lowerCamelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCamelCase , __lowerCamelCase = heap[smallest_child], positions[smallest_child] __lowerCamelCase , __lowerCamelCase = ( heap[start], positions[start], ) __lowerCamelCase , __lowerCamelCase = temp, tempa __lowerCamelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , a ) self.top_to_bottom(a , a , a , a ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Union[str, Any] , a : Any , a : str , a : Tuple ): """simple docstring""" __lowerCamelCase = position[index] while index != 0: __lowerCamelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCamelCase = heap[parent] __lowerCamelCase = position[parent] self.set_position(position[parent] , a ) else: __lowerCamelCase = val __lowerCamelCase = temp self.set_position(a , a ) break __lowerCamelCase = parent else: __lowerCamelCase = val __lowerCamelCase = temp self.set_position(a , 0 ) def SCREAMING_SNAKE_CASE__ ( self : str , a : List[Any] , a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = len(a ) // 2 - 1 for i in range(a , -1 , -1 ): self.top_to_bottom(a , a , len(a ) , a ) def SCREAMING_SNAKE_CASE__ ( self : Dict , a : List[str] , a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = positions[0] __lowerCamelCase = sys.maxsize self.top_to_bottom(a , 0 , len(a ) , a ) return temp def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[int]: __lowerCamelCase = Heap() __lowerCamelCase = [0] * len(UpperCamelCase__ ) __lowerCamelCase = [-1] * len(UpperCamelCase__ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCamelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCamelCase = [] for vertex in range(len(UpperCamelCase__ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCamelCase__ ) heap.node_position.append(UpperCamelCase__ ) __lowerCamelCase = [] __lowerCamelCase = 1 __lowerCamelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCamelCase = 0 __lowerCamelCase = distance heap.heapify(UpperCamelCase__ , UpperCamelCase__ ) for _ in range(1 , len(UpperCamelCase__ ) ): __lowerCamelCase = heap.delete_minimum(UpperCamelCase__ , UpperCamelCase__ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCamelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCamelCase__ )] ): __lowerCamelCase = distance heap.bottom_to_top( UpperCamelCase__ , heap.get_position(UpperCamelCase__ ) , UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > __UpperCAmelCase =int(input("Enter number of edges: ").strip()) __UpperCAmelCase =defaultdict(list) for _ in range(edges_number): __UpperCAmelCase =[int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
546
'''simple docstring''' import numpy as np def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> str: __lowerCamelCase = int(np.ceil((x_end - xa) / h ) ) __lowerCamelCase = np.zeros((n + 1,) ) __lowerCamelCase = ya __lowerCamelCase = xa for k in range(UpperCamelCase__ ): __lowerCamelCase = f(UpperCamelCase__ , y[k] ) __lowerCamelCase = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __lowerCamelCase = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __lowerCamelCase = f(x + h , y[k] + h * ka ) __lowerCamelCase = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
546
1
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) ->float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue UpperCAmelCase = cst_fwd.get(lowerCAmelCase_ , np.inf ) UpperCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) UpperCAmelCase = new_cost_f UpperCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: UpperCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ->int: UpperCAmelCase = -1 UpperCAmelCase = set() UpperCAmelCase = set() UpperCAmelCase = {source: 0} UpperCAmelCase = {destination: 0} UpperCAmelCase = {source: None} UpperCAmelCase = {destination: None} UpperCAmelCase = PriorityQueue() UpperCAmelCase = PriorityQueue() UpperCAmelCase = 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 = queue_forward.get() visited_forward.add(lowerCAmelCase_ ) UpperCAmelCase , UpperCAmelCase = queue_backward.get() visited_backward.add(lowerCAmelCase_ ) UpperCAmelCase = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) UpperCAmelCase = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: UpperCAmelCase = shortest_distance return shortest_path_distance __a = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } __a = { """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()
719
from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""", } class __lowercase ( __snake_case ): UpperCamelCase = '''nllb-moe''' UpperCamelCase = ['''past_key_values'''] UpperCamelCase = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : Optional[int] , __lowerCamelCase : Optional[Any]=1_2_8_1_1_2 , __lowerCamelCase : Dict=1_0_2_4 , __lowerCamelCase : Optional[int]=1_2 , __lowerCamelCase : Union[str, Any]=4_0_9_6 , __lowerCamelCase : List[str]=1_6 , __lowerCamelCase : List[str]=1_2 , __lowerCamelCase : int=4_0_9_6 , __lowerCamelCase : Tuple=1_6 , __lowerCamelCase : str=0.05 , __lowerCamelCase : List[str]=0.05 , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : str="relu" , __lowerCamelCase : Dict=1_0_2_4 , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : Optional[int]=0.1 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Optional[Any]=0.02 , __lowerCamelCase : Dict=2 , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Any=False , __lowerCamelCase : Tuple="float32" , __lowerCamelCase : Any=False , __lowerCamelCase : Optional[int]=1_2_8 , __lowerCamelCase : List[str]=6_4 , __lowerCamelCase : List[Any]=4 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : str=0.001 , __lowerCamelCase : Optional[int]=0.001 , __lowerCamelCase : Tuple="all" , __lowerCamelCase : Any=False , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : List[str]=1.0 , __lowerCamelCase : Dict=0.2 , __lowerCamelCase : Union[str, Any]=1 , __lowerCamelCase : int=0 , __lowerCamelCase : Dict=2 , __lowerCamelCase : int=False , **__lowerCamelCase : str , ) -> int: """simple docstring""" UpperCAmelCase = vocab_size UpperCAmelCase = max_position_embeddings UpperCAmelCase = d_model UpperCAmelCase = encoder_ffn_dim UpperCAmelCase = encoder_layers UpperCAmelCase = encoder_attention_heads UpperCAmelCase = decoder_ffn_dim UpperCAmelCase = decoder_layers UpperCAmelCase = decoder_attention_heads UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = activation_function UpperCAmelCase = init_std UpperCAmelCase = encoder_layerdrop UpperCAmelCase = decoder_layerdrop UpperCAmelCase = use_cache UpperCAmelCase = encoder_layers UpperCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase = router_z_loss_coef UpperCAmelCase = router_aux_loss_coef UpperCAmelCase = decoder_sparse_step UpperCAmelCase = encoder_sparse_step UpperCAmelCase = num_experts UpperCAmelCase = expert_capacity UpperCAmelCase = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) UpperCAmelCase = router_dtype UpperCAmelCase = router_ignore_padding_tokens UpperCAmelCase = batch_prioritized_routing UpperCAmelCase = second_expert_policy UpperCAmelCase = normalize_router_prob_before_dropping UpperCAmelCase = moe_eval_capacity_token_fraction UpperCAmelCase = moe_token_dropout UpperCAmelCase = output_router_logits super().__init__( pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , is_encoder_decoder=__lowerCamelCase , decoder_start_token_id=__lowerCamelCase , **__lowerCamelCase , )
627
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP 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 A ( _a ,unittest.TestCase ): lowercase_ = KandinskyImgaImgPipeline lowercase_ = ['prompt', 'image_embeds', 'negative_image_embeds', 'image'] lowercase_ = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', ] lowercase_ = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] lowercase_ = False @property def __lowerCAmelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Dict ) -> Optional[int]: """simple docstring""" return self.time_input_dim @property def __lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : int ) -> Optional[Any]: """simple docstring""" return 1_00 @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" _a = XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) _a = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=10_05 , ) _a = MultilingualCLIP(lowerCAmelCase_ ) _a = text_encoder.eval() return text_encoder @property def __lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) _a = { '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_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''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } _a = UNetaDConditionModel(**lowerCAmelCase_ ) return model @property def __lowerCAmelCase ( self : Optional[Any] ) -> int: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __lowerCAmelCase ( self : Any ) -> str: """simple docstring""" torch.manual_seed(0 ) _a = VQModel(**self.dummy_movq_kwargs ) return model def __lowerCAmelCase ( self : int ) -> str: """simple docstring""" _a = self.dummy_text_encoder _a = self.dummy_tokenizer _a = self.dummy_unet _a = self.dummy_movq _a = { '''num_train_timesteps''': 10_00, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_0_0_8_5, '''beta_end''': 0.0_1_2, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } _a = DDIMScheduler(**lowerCAmelCase_ ) _a = { '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __lowerCAmelCase ( self : Union[str, Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : List[Any]=0 ) -> List[str]: """simple docstring""" _a = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(lowerCAmelCase_ ) ).to(lowerCAmelCase_ ) _a = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(lowerCAmelCase_ ) # create init_image _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowerCAmelCase_ ) ).to(lowerCAmelCase_ ) _a = image.cpu().permute(0 , 2 , 3 , 1 )[0] _a = Image.fromarray(np.uinta(lowerCAmelCase_ ) ).convert('''RGB''' ).resize((2_56, 2_56) ) if str(lowerCAmelCase_ ).startswith('''mps''' ): _a = torch.manual_seed(lowerCAmelCase_ ) else: _a = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _a = { '''prompt''': '''horse''', '''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 __lowerCAmelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" _a = '''cpu''' _a = self.get_dummy_components() _a = self.pipeline_class(**lowerCAmelCase_ ) _a = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = pipe(**self.get_dummy_inputs(lowerCAmelCase_ ) ) _a = output.images _a = pipe( **self.get_dummy_inputs(lowerCAmelCase_ ) , return_dict=lowerCAmelCase_ , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) 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 A ( unittest.TestCase ): def __lowerCAmelCase ( self : Optional[Any] ) -> Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" _a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/kandinsky_img2img_frog.npy''' ) _a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) _a = '''A red cartoon frog, 4k''' _a = KandinskyPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(lowerCAmelCase_ ) _a = KandinskyImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1''' , torch_dtype=torch.floataa ) _a = pipeline.to(lowerCAmelCase_ ) pipeline.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = torch.Generator(device='''cpu''' ).manual_seed(0 ) _a , _a = pipe_prior( lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() _a = pipeline( lowerCAmelCase_ , image=lowerCAmelCase_ , image_embeds=lowerCAmelCase_ , negative_image_embeds=lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type='''np''' , ) _a = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ )
22
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class a_ ( unittest.TestCase ): def lowerCAmelCase( self : int ): """simple docstring""" snake_case : str = tempfile.mkdtemp() # fmt: off snake_case : str = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on snake_case : Optional[int] = 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] ) ) snake_case : str = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } snake_case : Optional[Any] = os.path.join(self.tmpdirname , UpperCAmelCase__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] , **UpperCAmelCase__ : Any ): """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def lowerCAmelCase( self : Dict , **UpperCAmelCase__ : str ): """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase( self : str ): """simple docstring""" snake_case : str = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case : Tuple = [Image.fromarray(np.moveaxis(UpperCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : str = self.get_tokenizer() snake_case : List[str] = self.get_image_processor() snake_case : Tuple = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) processor.save_pretrained(self.tmpdirname ) snake_case : Dict = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case : List[str] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) snake_case : Any = self.get_image_processor(do_normalize=UpperCAmelCase__ , padding_value=1.0 ) snake_case : Tuple = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=UpperCAmelCase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Optional[Any] = self.get_image_processor() snake_case : Any = self.get_tokenizer() snake_case : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) snake_case : Optional[Any] = self.prepare_image_inputs() snake_case : List[Any] = image_processor(UpperCAmelCase__ , return_tensors='''np''' ) snake_case : Union[str, Any] = processor(images=UpperCAmelCase__ , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Any = self.get_image_processor() snake_case : str = self.get_tokenizer() snake_case : str = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) snake_case : Dict = '''lower newer''' snake_case : List[str] = processor(text=UpperCAmelCase__ ) snake_case : Dict = tokenizer(UpperCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = self.get_image_processor() snake_case : Tuple = self.get_tokenizer() snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) snake_case : Optional[Any] = '''lower newer''' snake_case : List[Any] = self.prepare_image_inputs() snake_case : List[str] = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(UpperCAmelCase__ ): processor() def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : int = self.get_image_processor() snake_case : Dict = self.get_tokenizer() snake_case : List[Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) snake_case : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case : Optional[int] = processor.batch_decode(UpperCAmelCase__ ) snake_case : str = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Tuple = self.get_image_processor() snake_case : Tuple = self.get_tokenizer() snake_case : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) snake_case : str = '''lower newer''' snake_case : Optional[Any] = self.prepare_image_inputs() snake_case : Union[str, Any] = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
598
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool lowercase_ = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta\'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class __A ( _a ): '''simple docstring''' __lowerCamelCase : Any = 'facebook/nllb-200-distilled-600M' __lowerCamelCase : Any = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) __lowerCamelCase : Dict = 'translator' __lowerCamelCase : Dict = AutoTokenizer __lowerCamelCase : Any = AutoModelForSeqaSeqLM __lowerCamelCase : Dict = LANGUAGE_CODES __lowerCamelCase : List[Any] = ['text', 'text', 'text'] __lowerCamelCase : Optional[Any] = ['text'] def a__ (self , A , A , A ) -> List[Any]: """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(f'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'''{tgt_lang} is not a supported language.''' ) _a = self.lang_to_code[src_lang] _a = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( _A , return_tensors='''pt''' , src_lang=_A , tgt_lang=_A ) def a__ (self , A ) -> Optional[int]: """simple docstring""" return self.model.generate(**_A ) def a__ (self , A ) -> Optional[Any]: """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=_A )
714
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests lowercase_ = open # noqa: we just need to have a builtin inside this module to test it properly
352
0
"""simple docstring""" import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _lowerCAmelCase ( snake_case_ , unittest.TestCase ): __UpperCAmelCase : Union[str, Any] = PhobertTokenizer __UpperCAmelCase : Any = False def lowerCamelCase ( self ) -> int: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case : Optional[int] = ["T@@", "i", "I", "R@@", "r", "e@@"] snake_case : List[Any] = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) snake_case : Tuple = ["#version: 0.2", "l à</w>"] snake_case : Union[str, Any] = {"unk_token": "<unk>"} snake_case : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) snake_case : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(F'{token} {vocab_tokens[token]}\n' ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCamelCase__ ) ) def lowerCamelCase ( self , **UpperCamelCase__ ) -> Union[str, Any]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def lowerCamelCase ( self , UpperCamelCase__ ) -> List[Any]: '''simple docstring''' snake_case : Union[str, Any] = "Tôi là VinAI Research" snake_case : List[str] = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>" return input_text, output_text def lowerCamelCase ( self ) -> Any: '''simple docstring''' snake_case : Any = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case : List[str] = "Tôi là VinAI Research" snake_case : Tuple = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split() snake_case : str = tokenizer.tokenize(UpperCamelCase__ ) print(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) snake_case : Any = tokens + [tokenizer.unk_token] snake_case : Tuple = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , UpperCamelCase__ )
178
"""simple docstring""" __snake_case = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def __lowerCAmelCase ( ) -> None: """simple docstring""" snake_case : str = input("Enter message: " ) snake_case : Tuple = input("Enter key [alphanumeric]: " ) snake_case : Union[str, Any] = input("Encrypt/Decrypt [e/d]: " ) if mode.lower().startswith("e" ): snake_case : str = "encrypt" snake_case : Optional[int] = encrypt_message(lowercase , lowercase ) elif mode.lower().startswith("d" ): snake_case : List[Any] = "decrypt" snake_case : Tuple = decrypt_message(lowercase , lowercase ) print(F'\n{mode.title()}ed message:' ) print(lowercase ) def __lowerCAmelCase ( lowercase : str , lowercase : str ) -> str: """simple docstring""" return translate_message(lowercase , lowercase , "encrypt" ) def __lowerCAmelCase ( lowercase : str , lowercase : str ) -> str: """simple docstring""" return translate_message(lowercase , lowercase , "decrypt" ) def __lowerCAmelCase ( lowercase : str , lowercase : str , lowercase : str ) -> str: """simple docstring""" snake_case : List[Any] = [] snake_case : List[str] = 0 snake_case : List[Any] = key.upper() for symbol in message: snake_case : Optional[int] = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(lowercase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(lowercase ): snake_case : List[str] = 0 else: translated.append(lowercase ) return "".join(lowercase ) if __name__ == "__main__": main()
178
1
from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase_ ( _a): def __init__( self : List[Any] , __A : int , __A : Any ) ->Optional[Any]: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM a__ :List[str] = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self : Optional[Any] , __A : int = 1 , __A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A : float = 0.0 , __A : int = 50 , __A : Optional[bool] = None , __A : Optional[str] = "pil" , __A : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: """simple docstring""" if isinstance(self.unet.config.sample_size , __A ): a__ :str = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: a__ :str = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) a__ :Optional[int] = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output a__ :Optional[Any] = self.unet(__A , __A ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 a__ :Union[str, Any] = self.scheduler.step( __A , __A , __A , eta=__A , use_clipped_model_output=__A , generator=__A ).prev_sample a__ :List[str] = (image / 2 + 0.5).clamp(0 , 1 ) a__ :Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ :List[Any] = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
373
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case__ = { '''configuration_mgp_str''': ['''MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MgpstrConfig'''], '''processing_mgp_str''': ['''MgpstrProcessor'''], '''tokenization_mgp_str''': ['''MgpstrTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ = [ '''MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MgpstrModel''', '''MgpstrPreTrainedModel''', '''MgpstrForSceneTextRecognition''', ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys snake_case__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
373
1
from __future__ import annotations def _lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Dict: if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): UpperCamelCase__ : List[Any] = array[indexa], array[indexa] def _lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Tuple: if length > 1: UpperCamelCase__ : Any = int(length / 2 ) for i in range(__SCREAMING_SNAKE_CASE , low + middle ): comp_and_swap(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , i + middle , __SCREAMING_SNAKE_CASE ) bitonic_merge(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) bitonic_merge(__SCREAMING_SNAKE_CASE , low + middle , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Dict: if length > 1: UpperCamelCase__ : Optional[int] = int(length / 2 ) bitonic_sort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 1 ) bitonic_sort(__SCREAMING_SNAKE_CASE , low + middle , __SCREAMING_SNAKE_CASE , 0 ) bitonic_merge(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase__ : Optional[Any] = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase__ : str = [int(item.strip()) for item in user_input.split(''',''')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('''\nSorted array in ascending order is: ''', end='''''') print(*unsorted, sep=''', ''') bitonic_merge(unsorted, 0, len(unsorted), 0) print('''Sorted array in descending order is: ''', end='''''') print(*unsorted, sep=''', ''')
410
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase : Optional[int] = logging.get_logger(__name__) lowerCAmelCase : List[Any] = { 'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json', 'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json', 'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json', 'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json', 'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json', 'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json', 'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json', 'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json', 'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json', 'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json', } class _A ( __magic_name__): SCREAMING_SNAKE_CASE : Any = '''xlm''' SCREAMING_SNAKE_CASE : Union[str, Any] = { '''hidden_size''': '''emb_dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', '''n_words''': '''vocab_size''', # For backward compatibility } def __init__( self , _SCREAMING_SNAKE_CASE=3_0145 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2048**-0.5 , _SCREAMING_SNAKE_CASE=1e-12 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="first" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0 , **_SCREAMING_SNAKE_CASE , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = emb_dim SCREAMING_SNAKE_CASE_ : Optional[int] = n_layers SCREAMING_SNAKE_CASE_ : List[str] = n_heads SCREAMING_SNAKE_CASE_ : Tuple = dropout SCREAMING_SNAKE_CASE_ : List[Any] = attention_dropout SCREAMING_SNAKE_CASE_ : int = gelu_activation SCREAMING_SNAKE_CASE_ : Tuple = sinusoidal_embeddings SCREAMING_SNAKE_CASE_ : List[Any] = causal SCREAMING_SNAKE_CASE_ : Tuple = asm SCREAMING_SNAKE_CASE_ : Dict = n_langs SCREAMING_SNAKE_CASE_ : str = use_lang_emb SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Optional[int] = bos_index SCREAMING_SNAKE_CASE_ : List[str] = eos_index SCREAMING_SNAKE_CASE_ : List[str] = pad_index SCREAMING_SNAKE_CASE_ : Dict = unk_index SCREAMING_SNAKE_CASE_ : str = mask_index SCREAMING_SNAKE_CASE_ : List[Any] = is_encoder SCREAMING_SNAKE_CASE_ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Any = embed_init_std SCREAMING_SNAKE_CASE_ : int = init_std SCREAMING_SNAKE_CASE_ : Dict = summary_type SCREAMING_SNAKE_CASE_ : Any = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_proj_to_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[Any] = start_n_top SCREAMING_SNAKE_CASE_ : Optional[int] = end_n_top SCREAMING_SNAKE_CASE_ : Optional[int] = mask_token_id SCREAMING_SNAKE_CASE_ : int = lang_id if "n_words" in kwargs: SCREAMING_SNAKE_CASE_ : List[str] = kwargs['n_words'] super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) class _A ( __magic_name__): @property def UpperCAmelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : List[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE_ : int = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
511
0
import requests from bsa import BeautifulSoup def _UpperCAmelCase (UpperCamelCase_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' _lowerCAmelCase : Optional[int] = BeautifulSoup(requests.get(UpperCamelCase_ ).text , """html.parser""" ) _lowerCAmelCase : Optional[Any] = soup.findAll("""h1""" ) _lowerCAmelCase : List[Any] = soup.findAll("""div""" , {"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" , {"""class""": """panel-title"""} ) values += soup.findAll("""div""" , {"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(UpperCamelCase_ , UpperCamelCase_ )} if __name__ == "__main__": print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n") for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
710
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case : def __init__( self : str , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[str]=3 , _UpperCAmelCase : List[str]=32 , _UpperCAmelCase : str=3 , _UpperCAmelCase : Tuple=10 , _UpperCAmelCase : Optional[Any]=[10, 20, 30, 40] , _UpperCAmelCase : int=[1, 1, 2, 1] , _UpperCAmelCase : str=True , _UpperCAmelCase : List[str]=True , _UpperCAmelCase : str="relu" , _UpperCAmelCase : int=3 , _UpperCAmelCase : int=None , ) -> Optional[Any]: '''simple docstring''' _lowerCAmelCase : Dict = parent _lowerCAmelCase : int = batch_size _lowerCAmelCase : List[str] = image_size _lowerCAmelCase : Optional[int] = num_channels _lowerCAmelCase : List[str] = embeddings_size _lowerCAmelCase : int = hidden_sizes _lowerCAmelCase : str = depths _lowerCAmelCase : int = is_training _lowerCAmelCase : Dict = use_labels _lowerCAmelCase : Dict = hidden_act _lowerCAmelCase : Dict = num_labels _lowerCAmelCase : List[Any] = scope _lowerCAmelCase : Optional[int] = len(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: '''simple docstring''' _lowerCAmelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : Tuple = None if self.use_labels: _lowerCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) _lowerCAmelCase : Dict = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: '''simple docstring''' return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE ( self : List[str] , _UpperCAmelCase : int , _UpperCAmelCase : str , _UpperCAmelCase : Union[str, Any] ) -> Optional[int]: '''simple docstring''' _lowerCAmelCase : Optional[Any] = TFResNetModel(config=_UpperCAmelCase ) _lowerCAmelCase : Union[str, Any] = model(_UpperCAmelCase ) # 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 : Optional[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[Any] ) -> Optional[Any]: '''simple docstring''' _lowerCAmelCase : Optional[int] = self.num_labels _lowerCAmelCase : Any = TFResNetForImageClassification(_UpperCAmelCase ) _lowerCAmelCase : str = model(_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: '''simple docstring''' _lowerCAmelCase : Any = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[str] = config_and_inputs _lowerCAmelCase : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __snake_case (_a , _a , unittest.TestCase ): lowerCAmelCase__ = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () lowerCAmelCase__ = ( {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification} if is_tf_available() else {} ) lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : int ) -> int: '''simple docstring''' _lowerCAmelCase : Optional[int] = TFResNetModelTester(self ) _lowerCAmelCase : Union[str, Any] = ConfigTester(self , config_class=_UpperCAmelCase , has_text_modality=_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> 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 SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: '''simple docstring''' return @unittest.skip(reason="""ResNet does not use inputs_embeds""" ) def SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason="""ResNet does not support input and output embeddings""" ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any: '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Any = model_class(_UpperCAmelCase ) _lowerCAmelCase : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : Tuple = [*signature.parameters.keys()] _lowerCAmelCase : Optional[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: '''simple docstring''' _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: '''simple docstring''' def check_hidden_states_output(_UpperCAmelCase : Tuple , _UpperCAmelCase : Tuple , _UpperCAmelCase : Tuple ): _lowerCAmelCase : Dict = model_class(_UpperCAmelCase ) _lowerCAmelCase : Optional[int] = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase ) ) _lowerCAmelCase : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowerCAmelCase : Dict = self.model_tester.num_stages self.assertEqual(len(_UpperCAmelCase ) , expected_num_stages + 1 ) # ResNet'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 : Any = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase : str = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: _lowerCAmelCase : Tuple = layer_type _lowerCAmelCase : Any = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase : Any = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Any: '''simple docstring''' _lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: '''simple docstring''' for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : Dict = TFResNetModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def _UpperCAmelCase (): '''simple docstring''' _lowerCAmelCase : Optional[int] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __snake_case (unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: '''simple docstring''' _lowerCAmelCase : Dict = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) _lowerCAmelCase : Optional[int] = self.default_image_processor _lowerCAmelCase : int = prepare_img() _lowerCAmelCase : int = image_processor(images=_UpperCAmelCase , return_tensors="""tf""" ) # forward pass _lowerCAmelCase : int = model(**_UpperCAmelCase ) # verify the logits _lowerCAmelCase : Union[str, Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _UpperCAmelCase ) _lowerCAmelCase : Any = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _UpperCAmelCase , atol=1E-4 ) )
196
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase : Tuple = logging.get_logger(__name__) _lowerCAmelCase : Optional[Any] = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class lowerCAmelCase ( __UpperCamelCase ): '''simple docstring''' snake_case = 'distilbert' snake_case = { 'hidden_size': 'dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', } def __init__( self : int , __snake_case : Optional[int]=30522 , __snake_case : Tuple=512 , __snake_case : Optional[Any]=False , __snake_case : Any=6 , __snake_case : int=12 , __snake_case : List[Any]=768 , __snake_case : Optional[int]=4 * 768 , __snake_case : Optional[Any]=0.1 , __snake_case : List[Any]=0.1 , __snake_case : Tuple="gelu" , __snake_case : List[Any]=0.02 , __snake_case : Optional[Any]=0.1 , __snake_case : str=0.2 , __snake_case : Optional[Any]=0 , **__snake_case : List[str] , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase = vocab_size lowerCamelCase = max_position_embeddings lowerCamelCase = sinusoidal_pos_embds lowerCamelCase = n_layers lowerCamelCase = n_heads lowerCamelCase = dim lowerCamelCase = hidden_dim lowerCamelCase = dropout lowerCamelCase = attention_dropout lowerCamelCase = activation lowerCamelCase = initializer_range lowerCamelCase = qa_dropout lowerCamelCase = seq_classif_dropout super().__init__(**__snake_case , pad_token_id=__snake_case ) class lowerCAmelCase ( __UpperCamelCase ): '''simple docstring''' @property def lowerCamelCase__ ( self : Any ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": lowerCamelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowerCamelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
246
from collections import deque def a_ ( UpperCamelCase_ : List[str] ) -> Optional[Any]: """simple docstring""" lowerCamelCase = len(UpperCamelCase_ ) lowerCamelCase = deque() lowerCamelCase = [False for _ in range(UpperCamelCase_ )] lowerCamelCase = [-1 for _ in range(UpperCamelCase_ )] lowerCamelCase = index_of[:] def strong_connect(UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] ): lowerCamelCase = index # the number when this node is seen lowerCamelCase = index # lowest rank node reachable from here index += 1 stack.append(UpperCamelCase_ ) lowerCamelCase = True for w in g[v]: if index_of[w] == -1: lowerCamelCase = strong_connect(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCamelCase = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowerCamelCase = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: lowerCamelCase = [] lowerCamelCase = stack.pop() lowerCamelCase = False component.append(UpperCamelCase_ ) while w != v: lowerCamelCase = stack.pop() lowerCamelCase = False component.append(UpperCamelCase_ ) components.append(UpperCamelCase_ ) return index lowerCamelCase = [] for v in range(UpperCamelCase_ ): if index_of[v] == -1: strong_connect(UpperCamelCase_ , 0 , UpperCamelCase_ ) return components def a_ ( UpperCamelCase_ : Dict , UpperCamelCase_ : List[str] ) -> Optional[int]: """simple docstring""" lowerCamelCase = [[] for _ in range(UpperCamelCase_ )] for u, v in edges: g[u].append(UpperCamelCase_ ) return g if __name__ == "__main__": # Test _lowerCAmelCase : Any = 7 _lowerCAmelCase : Optional[int] = [0, 0, 1, 2, 3, 3, 4, 4, 6] _lowerCAmelCase : Dict = [1, 3, 2, 0, 1, 4, 5, 6, 5] _lowerCAmelCase : Union[str, Any] = [(u, v) for u, v in zip(source, target)] _lowerCAmelCase : Tuple = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
246
1
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging A = logging.get_logger(__name__) class __snake_case ( a__): _lowerCAmelCase = ['''pixel_values'''] def __init__( self, A = True, A = 32, A=PILImageResampling.BILINEAR, A = True, **A, ): """simple docstring""" lowerCamelCase : Tuple = do_resize lowerCamelCase : int = do_rescale lowerCamelCase : str = size_divisor lowerCamelCase : Tuple = resample super().__init__(**A ) def UpperCAmelCase_ ( self, A, A, A, A = None, **A ): """simple docstring""" lowerCamelCase : Optional[Any] = get_image_size(A ) # Rounds the height and width down to the closest multiple of size_divisor lowerCamelCase : List[str] = height // size_divisor * size_divisor lowerCamelCase : List[Any] = width // size_divisor * size_divisor lowerCamelCase : str = resize(A, (new_h, new_w), resample=A, data_format=A, **A ) return image def UpperCAmelCase_ ( self, A, A, A = None, **A ): """simple docstring""" return rescale(image=A, scale=A, data_format=A, **A ) def UpperCAmelCase_ ( self, A, A = None, A = None, A=None, A = None, A = None, A = ChannelDimension.FIRST, **A, ): """simple docstring""" lowerCamelCase : Union[str, Any] = do_resize if do_resize is not None else self.do_resize lowerCamelCase : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase : Optional[Any] = size_divisor if size_divisor is not None else self.size_divisor lowerCamelCase : Tuple = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('size_divisor is required for resizing' ) lowerCamelCase : Union[str, Any] = make_list_of_images(A ) if not valid_images(A ): raise ValueError('Invalid image(s)' ) # All transformations expect numpy arrays. lowerCamelCase : Dict = [to_numpy_array(A ) for img in images] if do_resize: lowerCamelCase : Optional[int] = [self.resize(A, size_divisor=A, resample=A ) for image in images] if do_rescale: lowerCamelCase : Optional[int] = [self.rescale(A, scale=1 / 255 ) for image in images] lowerCamelCase : Optional[int] = [to_channel_dimension_format(A, A ) for image in images] lowerCamelCase : List[str] = {'pixel_values': images} return BatchFeature(data=A, tensor_type=A )
712
'''simple docstring''' def UpperCAmelCase ( UpperCAmelCase__ : int = 10_00): lowerCamelCase : Optional[Any] = 2**power lowerCamelCase : str = str(UpperCAmelCase__) lowerCamelCase : Union[str, Any] = list(UpperCAmelCase__) lowerCamelCase : Optional[Any] = 0 for i in list_num: sum_of_num += int(UpperCAmelCase__) return sum_of_num if __name__ == "__main__": A = int(input('Enter the power of 2: ').strip()) print('2 ^ ', power, ' = ', 2**power) A = solution(power) print('Sum of the digits is: ', result)
449
0
'''simple docstring''' import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() __A =2 class _snake_case : def __init__( self , *, # begin keyword-only arguments _lowerCamelCase="<s>" , _lowerCamelCase="<pad>" , _lowerCamelCase="</s>" , _lowerCamelCase="<unk>" , _lowerCamelCase=None , ): UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : List[str] = bos, unk, pad, eos UpperCAmelCase__ : Any = [] UpperCAmelCase__ : List[str] = [] UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : Union[str, Any] = self.add_symbol(_lowerCamelCase) UpperCAmelCase__ : Any = self.add_symbol(_lowerCamelCase) UpperCAmelCase__ : List[str] = self.add_symbol(_lowerCamelCase) UpperCAmelCase__ : str = self.add_symbol(_lowerCamelCase) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(_lowerCamelCase) UpperCAmelCase__ : Optional[Any] = len(self.symbols) def __eq__( self , _lowerCamelCase): return self.indices == other.indices def __getitem__( self , _lowerCamelCase): if idx < len(self.symbols): return self.symbols[idx] return self.unk_word def __len__( self): return len(self.symbols) def __contains__( self , _lowerCamelCase): return sym in self.indices @classmethod def snake_case__ ( cls , _lowerCamelCase): UpperCAmelCase__ : Dict = cls() d.add_from_file(_lowerCamelCase) return d def snake_case__ ( self , _lowerCamelCase , _lowerCamelCase=1 , _lowerCamelCase=False): if word in self.indices and not overwrite: UpperCAmelCase__ : Tuple = self.indices[word] UpperCAmelCase__ : Optional[int] = self.count[idx] + n return idx else: UpperCAmelCase__ : Union[str, Any] = len(self.symbols) UpperCAmelCase__ : Optional[int] = idx self.symbols.append(_lowerCamelCase) self.count.append(_lowerCamelCase) return idx def snake_case__ ( self , _lowerCamelCase): return 0 def snake_case__ ( self , _lowerCamelCase): if isinstance(_lowerCamelCase , _lowerCamelCase): try: with open(_lowerCamelCase , """r""" , encoding="""utf-8""") as fd: self.add_from_file(_lowerCamelCase) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception("""Incorrect encoding detected in {}, please rebuild the dataset""".format(_lowerCamelCase)) return UpperCAmelCase__ : Optional[int] = f.readlines() UpperCAmelCase__ : List[Any] = self._load_meta(_lowerCamelCase) for line in lines[indices_start_line:]: try: UpperCAmelCase__ , UpperCAmelCase__ : int = line.rstrip().rsplit(""" """ , 1) if field == "#fairseq:overwrite": UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ , UpperCAmelCase__ : int = line.rsplit(""" """ , 1) else: UpperCAmelCase__ : List[Any] = False UpperCAmelCase__ : int = int(_lowerCamelCase) UpperCAmelCase__ : Any = line if word in self and not overwrite: raise RuntimeError( """Duplicate word found when loading Dictionary: '{}'. """ """Duplicate words can overwrite earlier ones by adding the """ """#fairseq:overwrite flag at the end of the corresponding row """ """in the dictionary file. If using the Camembert model, please """ """download an updated copy of the model file.""".format(_lowerCamelCase)) self.add_symbol(_lowerCamelCase , n=_lowerCamelCase , overwrite=_lowerCamelCase) except ValueError: raise ValueError("""Incorrect dictionary format, expected '<token> <cnt> [flags]'""") def _UpperCamelCase ( UpperCamelCase__ ): # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} UpperCAmelCase__ : Optional[Any] = dict((re.sub(R"""@@$""" , """""" , UpperCamelCase__ ), v) if k.endswith("""@@""" ) else (re.sub(R"""$""" , """</w>""" , UpperCamelCase__ ), v) for k, v in d.items() ) UpperCAmelCase__ : int = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[f'''{k}</w>'''] UpperCAmelCase__ : str = d[k] # restore return da def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): # prep if not os.path.exists(UpperCamelCase__ ): raise ValueError(f'''path {biogpt_checkpoint_path} does not exist!''' ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) print(f'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models UpperCAmelCase__ : str = os.path.join(UpperCamelCase__ , """checkpoint.pt""" ) if not os.path.isfile(UpperCamelCase__ ): raise ValueError(f'''path to the file {checkpoint_file} does not exist!''' ) UpperCAmelCase__ : Any = torch.load(UpperCamelCase__ , map_location="""cpu""" ) UpperCAmelCase__ : Union[str, Any] = chkpt["""cfg"""]["""model"""] # dicts UpperCAmelCase__ : str = os.path.join(UpperCamelCase__ , """dict.txt""" ) if not os.path.isfile(UpperCamelCase__ ): raise ValueError(f'''path to the file {dict_file} does not exist!''' ) UpperCAmelCase__ : Tuple = Dictionary.load(UpperCamelCase__ ) UpperCAmelCase__ : Union[str, Any] = rewrite_dict_keys(src_dict.indices ) UpperCAmelCase__ : Union[str, Any] = len(UpperCamelCase__ ) UpperCAmelCase__ : int = os.path.join(UpperCamelCase__ , VOCAB_FILES_NAMES["""vocab_file"""] ) print(f'''Generating {src_vocab_file} of {src_vocab_size} records''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCamelCase__ , ensure_ascii=UpperCamelCase__ , indent=UpperCamelCase__ ) ) # merges_file (bpecodes) UpperCAmelCase__ : Optional[int] = os.path.join(UpperCamelCase__ , """bpecodes""" ) if not os.path.isfile(UpperCamelCase__ ): raise ValueError(f'''path to the file {bpecodes_file} does not exist!''' ) UpperCAmelCase__ : Dict = os.path.join(UpperCamelCase__ , VOCAB_FILES_NAMES["""merges_file"""] ) shutil.copyfile(UpperCamelCase__ , UpperCamelCase__ ) # model config UpperCAmelCase__ : str = os.path.join(UpperCamelCase__ , """config.json""" ) UpperCAmelCase__ : Any = { """activation_dropout""": args["""activation_dropout"""], """architectures""": ["""BioGptForCausalLM"""], """attention_probs_dropout_prob""": args["""attention_dropout"""], """bos_token_id""": 0, """eos_token_id""": 2, """hidden_act""": args["""activation_fn"""], """hidden_dropout_prob""": args["""dropout"""], """hidden_size""": args["""decoder_embed_dim"""], """initializer_range""": 0.02, """intermediate_size""": args["""decoder_ffn_embed_dim"""], """layer_norm_eps""": 1e-12, """layerdrop""": args["""decoder_layerdrop"""], """max_position_embeddings""": args["""max_target_positions"""], """model_type""": """biogpt""", """num_attention_heads""": args["""decoder_attention_heads"""], """num_hidden_layers""": args["""decoder_layers"""], """pad_token_id""": 1, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_decoder_input_output_embed"""], """vocab_size""": src_vocab_size, } # good hparam defaults to start with print(f'''Generating {biogpt_model_config_file}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCamelCase__ , ensure_ascii=UpperCamelCase__ , indent=UpperCamelCase__ ) ) # tokenizer config UpperCAmelCase__ : Any = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : str = { """bos_token""": """<s>""", """eos_token""": """</s>""", """model_max_length""": 1_0_2_4, """pad_token""": """<pad>""", """special_tokens_map_file""": None, """tokenizer_class""": """BioGptTokenizer""", """unk_token""": """<unk>""", } print(f'''Generating {biogpt_tokenizer_config_file}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCamelCase__ , ensure_ascii=UpperCamelCase__ , indent=UpperCamelCase__ ) ) # model UpperCAmelCase__ : List[str] = chkpt["""model"""] # remove unneeded keys UpperCAmelCase__ : Dict = [ """decoder.version""", ] for k in ignore_keys: model_state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : Tuple = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith("""output_projection.weight""" ): UpperCAmelCase__ : Union[str, Any] = model_state_dict.pop(UpperCamelCase__ ) else: UpperCAmelCase__ : List[Any] = model_state_dict.pop(UpperCamelCase__ ) UpperCAmelCase__ : str = BioGptConfig.from_pretrained(UpperCamelCase__ ) UpperCAmelCase__ : Tuple = BioGptForCausalLM(UpperCamelCase__ ) # check that it loads ok model_new.load_state_dict(UpperCamelCase__ ) # save UpperCAmelCase__ : Any = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Generating {pytorch_weights_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) print("""Conversion is done!""" ) if __name__ == "__main__": __A =argparse.ArgumentParser() # Required parameters parser.add_argument( '--biogpt_checkpoint_path', default=None, type=str, required=True, help=( 'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,' ' bpecodes, etc.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __A =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
407
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _snake_case ( a__ ): lowerCAmelCase :UNetaDModel lowerCAmelCase :ScoreSdeVeScheduler def __init__( self , _lowerCamelCase , _lowerCamelCase): super().__init__() self.register_modules(unet=_lowerCamelCase , scheduler=_lowerCamelCase) @torch.no_grad() def __call__( self , _lowerCamelCase = 1 , _lowerCamelCase = 2000 , _lowerCamelCase = None , _lowerCamelCase = "pil" , _lowerCamelCase = True , **_lowerCamelCase , ): UpperCAmelCase__ : Union[str, Any] = self.unet.config.sample_size UpperCAmelCase__ : Any = (batch_size, 3, img_size, img_size) UpperCAmelCase__ : Optional[int] = self.unet UpperCAmelCase__ : Any = randn_tensor(_lowerCamelCase , generator=_lowerCamelCase) * self.scheduler.init_noise_sigma UpperCAmelCase__ : Optional[int] = sample.to(self.device) self.scheduler.set_timesteps(_lowerCamelCase) self.scheduler.set_sigmas(_lowerCamelCase) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)): UpperCAmelCase__ : List[str] = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device) # correction step for _ in range(self.scheduler.config.correct_steps): UpperCAmelCase__ : List[str] = self.unet(_lowerCamelCase , _lowerCamelCase).sample UpperCAmelCase__ : List[Any] = self.scheduler.step_correct(_lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase).prev_sample # prediction step UpperCAmelCase__ : Any = model(_lowerCamelCase , _lowerCamelCase).sample UpperCAmelCase__ : Union[str, Any] = self.scheduler.step_pred(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase) UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = output.prev_sample, output.prev_sample_mean UpperCAmelCase__ : Optional[Any] = sample_mean.clamp(0 , 1) UpperCAmelCase__ : List[str] = sample.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": UpperCAmelCase__ : str = self.numpy_to_pil(_lowerCamelCase) if not return_dict: return (sample,) return ImagePipelineOutput(images=_lowerCamelCase)
407
1
'''simple docstring''' def __snake_case ( _UpperCAmelCase : int = 100): UpperCamelCase = n * (n + 1) * (2 * n + 1) / 6 UpperCamelCase = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares) if __name__ == "__main__": print(F'''{solution() = }''')
721
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __snake_case ( ): UpperCamelCase = ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' )) # Optional arguments for the launch helper parser.add_argument('''--num_cores''', type=_UpperCAmelCase, default=1, help='''Number of TPU cores to use (1 or 8).''') # positional parser.add_argument( '''training_script''', type=_UpperCAmelCase, help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ), ) # rest from the training program parser.add_argument('''training_script_args''', nargs=_UpperCAmelCase) return parser.parse_args() def __snake_case ( ): UpperCamelCase = parse_args() # Import training_script as a module. UpperCamelCase = Path(args.training_script) sys.path.append(str(script_fpath.parent.resolve())) UpperCamelCase = script_fpath.stem UpperCamelCase = importlib.import_module(_UpperCAmelCase) # Patch sys.argv UpperCamelCase = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores)] xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores) if __name__ == "__main__": main()
350
0
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed _SCREAMING_SNAKE_CASE : Union[str, Any] = { 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __lowerCAmelCase ( __magic_name__ ): assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __lowerCAmelCase ( __magic_name__ , __magic_name__ ): if args.student_type == "roberta": _lowercase: Union[str, Any] = False elif args.student_type == "gpt2": _lowercase: List[str] = False def __lowerCAmelCase ( __magic_name__ , __magic_name__ ): if args.student_type == "roberta": _lowercase: Dict = False def __lowerCAmelCase ( ): _lowercase: Any = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=__magic_name__ , required=__magic_name__ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=__magic_name__ , required=__magic_name__ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=__magic_name__ , choices=["distilbert", "roberta", "gpt2"] , required=__magic_name__ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=__magic_name__ , required=__magic_name__ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=__magic_name__ , type=__magic_name__ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=__magic_name__ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=__magic_name__ , required=__magic_name__ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=__magic_name__ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=__magic_name__ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=__magic_name__ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=__magic_name__ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=__magic_name__ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=__magic_name__ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=__magic_name__ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=__magic_name__ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=__magic_name__ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=__magic_name__ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=__magic_name__ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=__magic_name__ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=__magic_name__ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=__magic_name__ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=__magic_name__ , default=5_0 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=__magic_name__ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=__magic_name__ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5e-4 , type=__magic_name__ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1e-6 , type=__magic_name__ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=__magic_name__ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=__magic_name__ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=__magic_name__ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=__magic_name__ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=__magic_name__ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=__magic_name__ , default=5_6 , help="Random seed" ) parser.add_argument("--log_interval" , type=__magic_name__ , default=5_0_0 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=__magic_name__ , default=4_0_0_0 , help="Checkpoint interval." ) _lowercase: str = parser.parse_args() sanity_checks(__magic_name__ ) # ARGS # init_gpu_params(__magic_name__ ) set_seed(__magic_name__ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(__magic_name__ ) , __magic_name__ , indent=4 ) git_log(args.dump_path ) _lowercase , _lowercase , _lowercase: List[Any] = MODEL_CLASSES[args.student_type] _lowercase , _lowercase , _lowercase: str = MODEL_CLASSES[args.teacher_type] # TOKENIZER # _lowercase: Optional[int] = teacher_tokenizer_class.from_pretrained(args.teacher_name ) _lowercase: Optional[int] = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): _lowercase: Optional[Any] = tokenizer.all_special_tokens.index(__magic_name__ ) _lowercase: List[Any] = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) _lowercase: int = special_tok_ids _lowercase: Optional[Any] = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , "rb" ) as fp: _lowercase: List[str] = pickle.load(__magic_name__ ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , "rb" ) as fp: _lowercase: Optional[Any] = pickle.load(__magic_name__ ) _lowercase: int = np.maximum(__magic_name__ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): _lowercase: str = 0.0 # do not predict special tokens _lowercase: int = torch.from_numpy(__magic_name__ ) else: _lowercase: Dict = None _lowercase: List[str] = LmSeqsDataset(params=__magic_name__ , data=__magic_name__ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) _lowercase: Dict = student_config_class.from_pretrained(args.student_config ) _lowercase: List[Any] = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) _lowercase: List[Any] = student_model_class.from_pretrained(args.student_pretrained_weights , config=__magic_name__ ) else: _lowercase: Union[str, Any] = student_model_class(__magic_name__ ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("Student loaded." ) # TEACHER # _lowercase: Dict = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__magic_name__ ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__magic_name__ , __magic_name__ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__magic_name__ , __magic_name__ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() _lowercase: List[str] = Distiller( params=__magic_name__ , dataset=__magic_name__ , token_probs=__magic_name__ , student=__magic_name__ , teacher=__magic_name__ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
226
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Union[str, Any] = { 'configuration_vision_text_dual_encoder': ['VisionTextDualEncoderConfig'], 'processing_vision_text_dual_encoder': ['VisionTextDualEncoderProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = ['VisionTextDualEncoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Tuple = ['FlaxVisionTextDualEncoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = ['TFVisionTextDualEncoderModel'] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
226
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { 'naver-clova-ix/donut-base': 'https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json', # See all Donut models at https://huggingface.co/models?filter=donut-swin } class _SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): a_ : Union[str, Any] = '''donut-swin''' a_ : int = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__(self , UpperCAmelCase=2_2_4 , UpperCAmelCase=4 , UpperCAmelCase=3 , UpperCAmelCase=9_6 , UpperCAmelCase=[2, 2, 6, 2] , UpperCAmelCase=[3, 6, 1_2, 2_4] , UpperCAmelCase=7 , UpperCAmelCase=4.0 , UpperCAmelCase=True , UpperCAmelCase=0.0 , UpperCAmelCase=0.0 , UpperCAmelCase=0.1 , UpperCAmelCase="gelu" , UpperCAmelCase=False , UpperCAmelCase=0.02 , UpperCAmelCase=1e-5 , **UpperCAmelCase , ): '''simple docstring''' super().__init__(**UpperCAmelCase) __UpperCAmelCase =image_size __UpperCAmelCase =patch_size __UpperCAmelCase =num_channels __UpperCAmelCase =embed_dim __UpperCAmelCase =depths __UpperCAmelCase =len(UpperCAmelCase) __UpperCAmelCase =num_heads __UpperCAmelCase =window_size __UpperCAmelCase =mlp_ratio __UpperCAmelCase =qkv_bias __UpperCAmelCase =hidden_dropout_prob __UpperCAmelCase =attention_probs_dropout_prob __UpperCAmelCase =drop_path_rate __UpperCAmelCase =hidden_act __UpperCAmelCase =use_absolute_embeddings __UpperCAmelCase =layer_norm_eps __UpperCAmelCase =initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __UpperCAmelCase =int(embed_dim * 2 ** (len(UpperCAmelCase) - 1))
142
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCamelCase_ = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' UpperCamelCase_ = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' UpperCamelCase_ = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' UpperCamelCase_ = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' UpperCamelCase_ = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _SCREAMING_SNAKE_CASE ( datasets.Metric ): def A__ (self): '''simple docstring''' return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Value('''string'''), }) , homepage='''https://github.com/openai/human-eval''' , codebase_urls=['''https://github.com/openai/human-eval'''] , reference_urls=['''https://github.com/openai/human-eval'''] , license=_LICENSE , ) def A__ (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=[1, 1_0, 1_0_0] , UpperCAmelCase=4 , UpperCAmelCase=3.0): '''simple docstring''' if os.getenv('''HF_ALLOW_CODE_EVAL''' , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError('''This metric is currently not supported on Windows.''') with ThreadPoolExecutor(max_workers=UpperCAmelCase) as executor: __UpperCAmelCase =[] __UpperCAmelCase =Counter() __UpperCAmelCase =0 __UpperCAmelCase =defaultdict(UpperCAmelCase) for task_id, (candidates, test_case) in enumerate(zip(UpperCAmelCase , UpperCAmelCase)): for candidate in candidates: __UpperCAmelCase =candidate + '''\n''' + test_case __UpperCAmelCase =(test_program, timeout, task_id, completion_id[task_id]) __UpperCAmelCase =executor.submit(UpperCAmelCase , *UpperCAmelCase) futures.append(UpperCAmelCase) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(UpperCAmelCase): __UpperCAmelCase =future.result() results[result["task_id"]].append((result['''completion_id'''], result)) __UpperCAmelCase , __UpperCAmelCase =[], [] for result in results.values(): result.sort() __UpperCAmelCase =[r[1]['''passed'''] for r in result] total.append(len(UpperCAmelCase)) correct.append(sum(UpperCAmelCase)) __UpperCAmelCase =np.array(UpperCAmelCase) __UpperCAmelCase =np.array(UpperCAmelCase) __UpperCAmelCase =k __UpperCAmelCase ={f"""pass@{k}""": estimate_pass_at_k(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase).mean() for k in ks if (total >= k).all()} return pass_at_k, results def SCREAMING_SNAKE_CASE ( snake_case__ , snake_case__ , snake_case__ ) -> str: def estimator(snake_case__ , snake_case__ , snake_case__ ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(snake_case__ , snake_case__ ): __UpperCAmelCase =itertools.repeat(snake_case__ , len(snake_case__ ) ) else: assert len(snake_case__ ) == len(snake_case__ ) __UpperCAmelCase =iter(snake_case__ ) return np.array([estimator(int(snake_case__ ) , int(snake_case__ ) , snake_case__ ) for n, c in zip(snake_case__ , snake_case__ )] )
142
1