code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = [ "decoder.version", "decoder.output_projection.weight", "_float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(lowercase , lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = emb.weight.shape SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(lowercase , lowercase , bias=lowercase ) SCREAMING_SNAKE_CASE : Any = emb.weight.data return lin_layer def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = torch.load(lowercase , map_location="cpu" ) SCREAMING_SNAKE_CASE : Optional[int] = Namespace(**checkpoint["cfg"]["model"] ) SCREAMING_SNAKE_CASE : str = checkpoint["model"] remove_ignore_keys_(lowercase ) SCREAMING_SNAKE_CASE : str = state_dict["decoder.embed_tokens.weight"].shape[0] SCREAMING_SNAKE_CASE : Any = {key.replace("decoder" , "model" ): val for key, val in state_dict.items()} SCREAMING_SNAKE_CASE : List[str] = XGLMConfig( vocab_size=lowercase , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="gelu" , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) SCREAMING_SNAKE_CASE : Tuple = XGLMForCausalLM(lowercase ) SCREAMING_SNAKE_CASE : List[Any] = model.load_state_dict(lowercase , strict=lowercase ) print(lowercase ) SCREAMING_SNAKE_CASE : int = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""fairseq_path""", type=str, help="""path to a model.pt on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() snake_case = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
62
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ : Any = '''image_segmenter''' UpperCamelCase_ : int = CLIPSegForImageSegmentation UpperCamelCase_ : Optional[Any] = ['''image''', '''text'''] UpperCamelCase_ : int = ['''image'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): with torch.no_grad(): SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits return logits def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
62
1
import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any]=13 , UpperCAmelCase_ : Any=7 , UpperCAmelCase_ : Union[str, Any]=6 , UpperCAmelCase_ : Optional[Any]=17 , UpperCAmelCase_ : Optional[Any]=23 , UpperCAmelCase_ : Optional[int]=11 , UpperCAmelCase_ : Any=True , ): SCREAMING_SNAKE_CASE : Optional[Any] = parent SCREAMING_SNAKE_CASE : Dict = batch_size SCREAMING_SNAKE_CASE : Tuple = seq_length SCREAMING_SNAKE_CASE : List[str] = act_dim SCREAMING_SNAKE_CASE : Optional[int] = state_dim SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = max_length SCREAMING_SNAKE_CASE : Optional[int] = is_training def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) SCREAMING_SNAKE_CASE : int = floats_tensor((self.batch_size, self.seq_length, 1) ) SCREAMING_SNAKE_CASE : Any = floats_tensor((self.batch_size, self.seq_length, 1) ) SCREAMING_SNAKE_CASE : List[str] = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) SCREAMING_SNAKE_CASE : str = random_attention_mask((self.batch_size, self.seq_length) ) SCREAMING_SNAKE_CASE : str = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def _A ( self : List[Any] ): return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] , ): SCREAMING_SNAKE_CASE : Dict = DecisionTransformerModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE : Any = { "states": states, "actions": actions, "rewards": rewards, "returns_to_go": returns_to_go, "timesteps": timesteps, "attention_mask": attention_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = (DecisionTransformerModel,) if is_torch_available() else () UpperCamelCase_ : Dict = () UpperCamelCase_ : Optional[int] = {'''feature-extraction''': DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids UpperCamelCase_ : str = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features UpperCamelCase_ : Tuple = False UpperCamelCase_ : str = False UpperCamelCase_ : Union[str, Any] = False UpperCamelCase_ : Optional[Any] = False UpperCamelCase_ : Tuple = False UpperCamelCase_ : Union[str, Any] = False UpperCamelCase_ : Optional[Any] = False UpperCamelCase_ : Dict = False UpperCamelCase_ : Optional[Any] = False def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : str = DecisionTransformerModelTester(self ) SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) @slow def _A ( self : str ): for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : int = DecisionTransformerModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _A ( self : str ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = [ "states", "actions", "rewards", "returns_to_go", "timesteps", "attention_mask", ] self.assertListEqual(arg_names[: len(UpperCAmelCase_ )] , UpperCAmelCase_ ) @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = 2 # number of steps of autoregressive prediction we will perform SCREAMING_SNAKE_CASE : Tuple = 10 # defined by the RL environment, may be normalized SCREAMING_SNAKE_CASE : int = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-expert" ) SCREAMING_SNAKE_CASE : int = model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = model.config torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = torch.randn(1 , 1 , config.state_dim ).to(device=UpperCAmelCase_ , dtype=torch.floataa ) # env.reset() SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[0.242_793, -0.28_693_074, 0.8_742_613], [0.67_815_274, -0.08_101_085, -0.12_952_147]] , device=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=torch.floataa ).reshape(1 , 1 , 1 ) SCREAMING_SNAKE_CASE : Tuple = state SCREAMING_SNAKE_CASE : str = torch.zeros(1 , 0 , config.act_dim , device=UpperCAmelCase_ , dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Optional[int] = torch.zeros(1 , 0 , device=UpperCAmelCase_ , dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Any = torch.tensor(0 , device=UpperCAmelCase_ , dtype=torch.long ).reshape(1 , 1 ) for step in range(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=UpperCAmelCase_ )] , dim=1 ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat([rewards, torch.zeros(1 , 1 , device=UpperCAmelCase_ )] , dim=1 ) SCREAMING_SNAKE_CASE : Dict = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = model( states=UpperCAmelCase_ , actions=UpperCAmelCase_ , rewards=UpperCAmelCase_ , returns_to_go=UpperCAmelCase_ , timesteps=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=UpperCAmelCase_ , dtype=torch.floataa ), 1.0, False, {}, ) SCREAMING_SNAKE_CASE : List[Any] = action_pred[0, -1] SCREAMING_SNAKE_CASE : str = torch.cat([states, state] , dim=1 ) SCREAMING_SNAKE_CASE : List[str] = returns_to_go[0, -1] - reward SCREAMING_SNAKE_CASE : Dict = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat( [timesteps, torch.ones((1, 1) , device=UpperCAmelCase_ , dtype=torch.long ) * (step + 1)] , dim=1 )
62
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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BlenderbotSmallTokenizer UpperCamelCase_ : int = False def _A ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] SCREAMING_SNAKE_CASE : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : List[Any] , **UpperCAmelCase_ : str ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : int = "adapt act apte" return input_text, output_text def _A ( self : str ): SCREAMING_SNAKE_CASE : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : List[str] = ["adapt", "act", "ap@@", "te"] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1384] SCREAMING_SNAKE_CASE : str = "I am a small frog." SCREAMING_SNAKE_CASE : List[Any] = tok([src_text] , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : int = tok.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) SCREAMING_SNAKE_CASE : Tuple = "I am a small frog ." SCREAMING_SNAKE_CASE : Optional[int] = "." SCREAMING_SNAKE_CASE : Dict = tok(UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : Optional[Any] = tok(UpperCAmelCase_ )["input_ids"] assert encoded[-1] == encoded_dot[0]
62
1
class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Dict ): SCREAMING_SNAKE_CASE : Optional[int] = {} def _A ( self : str ): print(self.vertex ) for i in self.vertex: print(UpperCAmelCase_ , " -> " , " -> ".join([str(UpperCAmelCase_ ) for j in self.vertex[i]] ) ) def _A ( self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : int ): # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(UpperCAmelCase_ ) else: # else make a new vertex SCREAMING_SNAKE_CASE : List[str] = [to_vertex] def _A ( self : int ): # visited array for storing already visited nodes SCREAMING_SNAKE_CASE : Any = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : list ): # mark start vertex as visited SCREAMING_SNAKE_CASE : Any = True print(UpperCAmelCase_ , end=" " ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(UpperCAmelCase_ , UpperCAmelCase_ ) if __name__ == "__main__": snake_case = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
62
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] snake_case = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = torch.load(lowercase , map_location="cpu" ) return sd def lowerCamelCase__ ( lowercase , lowercase , lowercase=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE : Union[str, Any] = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE : Any = new_key.replace(name_pair[0] , name_pair[1] ) SCREAMING_SNAKE_CASE : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE : Union[str, Any] = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = "pretraining" if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Any = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 512} SCREAMING_SNAKE_CASE : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = {"visual_embedding_dim": 2048} SCREAMING_SNAKE_CASE : str = "vqa_advanced" elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Tuple = {"visual_embedding_dim": 2048, "num_labels": 3129} SCREAMING_SNAKE_CASE : Optional[Any] = "vqa" elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = { "visual_embedding_dim": 1024, "num_labels": 2, } SCREAMING_SNAKE_CASE : Tuple = "nlvr" SCREAMING_SNAKE_CASE : List[Any] = VisualBertConfig(**lowercase ) # Load State Dict SCREAMING_SNAKE_CASE : List[str] = load_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Any = get_new_dict(lowercase , lowercase ) if model_type == "pretraining": SCREAMING_SNAKE_CASE : int = VisualBertForPreTraining(lowercase ) elif model_type == "vqa": SCREAMING_SNAKE_CASE : Tuple = VisualBertForQuestionAnswering(lowercase ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE : List[Any] = VisualBertForVisualReasoning(lowercase ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE : Optional[Any] = VisualBertForMultipleChoice(lowercase ) model.load_state_dict(lowercase ) # Save Checkpoints Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available snake_case = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] snake_case = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] snake_case = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): snake_case = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """JukeboxPriorConfig""", """JukeboxVQVAEConfig""", ], """tokenization_jukebox""": ["""JukeboxTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """JukeboxModel""", """JukeboxPreTrainedModel""", """JukeboxVQVAE""", """JukeboxPrior""", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
1
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "tf_padding" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "depth_multiplier" ) ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]=13 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : int=0.25 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : Dict=8 , UpperCAmelCase_ : Optional[int]=6 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : str="relu6" , UpperCAmelCase_ : List[str]=1280 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : int = depth_multiplier SCREAMING_SNAKE_CASE : str = depth_divisible_by SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth SCREAMING_SNAKE_CASE : int = expand_ratio SCREAMING_SNAKE_CASE : Tuple = tf_padding SCREAMING_SNAKE_CASE : List[str] = output_stride SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion SCREAMING_SNAKE_CASE : Any = finegrained_output SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = scope def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels, pixel_labels def _A ( self : Optional[int] ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Dict = MobileNetVaForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase_ : List[Any] = ( { '''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification, '''image-segmentation''': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Any = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : int = False UpperCamelCase_ : str = False def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def _A ( self : List[Any] ): pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def _A ( self : Dict ): pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def _A ( self : Union[str, Any] ): pass def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): def check_hidden_states_output(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 16 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : str = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def _A ( self : Optional[Any] ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : int = MobileNetVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Optional[int] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ ) # verify the logits SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : int = model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.tensor( [ [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]], [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]], [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
62
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ snake_case = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ snake_case = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _A ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def _A ( self : List[Any] , UpperCAmelCase_ : List[List[List[str]]] , UpperCAmelCase_ : List[List[str]] , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCAmelCase_ , hypotheses=UpperCAmelCase_ , min_len=UpperCAmelCase_ , max_len=UpperCAmelCase_ ) }
62
1
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel snake_case = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attention.self""", """self.proj""": """output.dense""", """attention.self_mask""": """attn_mask""", """mlp.fc1""": """intermediate.dense""", """mlp.fc2""": """output.dense""", """norm1""": """layernorm_before""", """norm2""": """layernorm_after""", """bn0""": """batch_norm""", } snake_case = AutoFeatureExtractor.from_pretrained("""laion/clap-htsat-unfused""", truncation="""rand_trunc""") def lowerCamelCase__ ( lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = create_model( "HTSAT-tiny" , "roberta" , lowercase , precision="fp32" , device="cuda:0" if torch.cuda.is_available() else "cpu" , enable_fusion=lowercase , fusion_type="aff_2d" if enable_fusion else None , ) return model, model_cfg def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = {} SCREAMING_SNAKE_CASE : Tuple = R".*sequential.(\d+).*" SCREAMING_SNAKE_CASE : Tuple = R".*_projection.(\d+).*" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: SCREAMING_SNAKE_CASE : List[str] = key.replace(lowercase , lowercase ) if re.match(lowercase , lowercase ): # replace sequential layers with list SCREAMING_SNAKE_CASE : Union[str, Any] = re.match(lowercase , lowercase ).group(1 ) SCREAMING_SNAKE_CASE : Tuple = key.replace(F'''sequential.{sequential_layer}.''' , F'''layers.{int(lowercase )//3}.linear.''' ) elif re.match(lowercase , lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(re.match(lowercase , lowercase ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... SCREAMING_SNAKE_CASE : List[Any] = 1 if projecton_layer == 0 else 2 SCREAMING_SNAKE_CASE : Tuple = key.replace(F'''_projection.{projecton_layer}.''' , F'''_projection.linear{transformers_projection_layer}.''' ) if "audio" and "qkv" in key: # split qkv into query key and value SCREAMING_SNAKE_CASE : List[Any] = value SCREAMING_SNAKE_CASE : List[str] = mixed_qkv.size(0 ) // 3 SCREAMING_SNAKE_CASE : str = mixed_qkv[:qkv_dim] SCREAMING_SNAKE_CASE : Optional[Any] = mixed_qkv[qkv_dim : qkv_dim * 2] SCREAMING_SNAKE_CASE : Any = mixed_qkv[qkv_dim * 2 :] SCREAMING_SNAKE_CASE : Any = query_layer SCREAMING_SNAKE_CASE : List[str] = key_layer SCREAMING_SNAKE_CASE : Union[str, Any] = value_layer else: SCREAMING_SNAKE_CASE : Union[str, Any] = value return model_state_dict def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = init_clap(lowercase , enable_fusion=lowercase ) clap_model.eval() SCREAMING_SNAKE_CASE : Optional[int] = clap_model.state_dict() SCREAMING_SNAKE_CASE : str = rename_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = ClapConfig() SCREAMING_SNAKE_CASE : Optional[Any] = enable_fusion SCREAMING_SNAKE_CASE : Dict = ClapModel(lowercase ) # ignore the spectrogram embedding layer model.load_state_dict(lowercase , strict=lowercase ) model.save_pretrained(lowercase ) transformers_config.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument("""--enable_fusion""", action="""store_true""", help="""Whether to enable fusion or not""") snake_case = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = row, column SCREAMING_SNAKE_CASE : Optional[Any] = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE : Optional[Any] = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = f'''%{max_element_length}s''' # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE : Optional[int] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Dict ): return str(self ) def _A ( self : Optional[int] , UpperCAmelCase_ : tuple[int, int] ): if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase_ : tuple[int, int] ): assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : int , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ): assert self.validate_indicies(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : Any = self[r, c] + another[r, c] return result def __neg__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ): return self + (-another) def __mul__( self : Dict , UpperCAmelCase_ : int | float | Matrix ): if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE : Any = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE : List[str] = f'''Unsupported type given for another ({type(UpperCAmelCase_ )})''' raise TypeError(UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : List[str] = self[r, c] return result def _A ( self : Union[str, Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE : Tuple = v.transpose() SCREAMING_SNAKE_CASE : int = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE : str = 1 print(F'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE : Optional[int] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 2, -3 SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase , lowercase )}''' ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() testa()
62
1
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = ['''torch''', '''torchsde'''] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any] ): requires_backends(self , ["torch", "torchsde"] ) @classmethod def _A ( cls : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Optional[int] ): requires_backends(cls , ["torch", "torchsde"] ) @classmethod def _A ( cls : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[str] ): requires_backends(cls , ["torch", "torchsde"] )
62
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } snake_case = { """junnyu/roformer_chinese_small""": 1_536, """junnyu/roformer_chinese_base""": 1_536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } snake_case = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = RoFormerTokenizer def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : List[str]="[UNK]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : Any="[PAD]" , UpperCAmelCase_ : List[str]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : List[str] , ): 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_ , ) SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase_ ) != strip_accents ): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : List[str] = strip_accents SCREAMING_SNAKE_CASE : Tuple = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : Tuple , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = d SCREAMING_SNAKE_CASE : Dict = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE : Any = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase_ ) ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _A ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : List[Any] = [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 _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Optional[int] = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
62
1
snake_case = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} snake_case = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Any = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(lowercase , lowercase , lowercase ) order.append(lowercase ) return order def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : List[Any] = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(lowercase , lowercase , lowercase ) return component def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = len(lowercase ) * [False] SCREAMING_SNAKE_CASE : dict[int, list[int]] = {vert: [] for vert in range(len(lowercase ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for i, was_visited in enumerate(lowercase ): if not was_visited: order += topology_sort(lowercase , lowercase , lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : List[str] = len(lowercase ) * [False] for i in range(len(lowercase ) ): SCREAMING_SNAKE_CASE : str = order[len(lowercase ) - i - 1] if not visited[vert]: SCREAMING_SNAKE_CASE : int = find_components(lowercase , lowercase , lowercase ) components_list.append(lowercase ) return components_list
62
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE : Optional[int] = str(abs(lowercase ) ) SCREAMING_SNAKE_CASE : str = [list(lowercase ) for char in range(len(lowercase ) )] for index in range(len(lowercase ) ): num_transpositions[index].pop(lowercase ) return max( int("".join(list(lowercase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
62
1
import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging snake_case = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = CLIPConfig UpperCamelCase_ : str = ['''CLIPEncoderLayer'''] def __init__( self : Optional[Any] , UpperCAmelCase_ : CLIPConfig ): super().__init__(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = CLIPVisionModelWithProjection(config.vision_config ) SCREAMING_SNAKE_CASE : List[str] = nn.Linear(config.vision_config.projection_dim , 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(config.vision_config.projection_dim , 1 ) @torch.no_grad() def _A ( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple=0.5 , UpperCAmelCase_ : Optional[Any]=0.5 ): SCREAMING_SNAKE_CASE : int = self.vision_model(UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.p_head(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = nsfw_detected.flatten() SCREAMING_SNAKE_CASE : str = nsfw_detected > p_threshold SCREAMING_SNAKE_CASE : str = nsfw_detected.tolist() if any(UpperCAmelCase_ ): logger.warning( "Potential NSFW content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, nsfw_detected_ in enumerate(UpperCAmelCase_ ): if nsfw_detected_: SCREAMING_SNAKE_CASE : Tuple = np.zeros(images[idx].shape ) SCREAMING_SNAKE_CASE : Optional[Any] = self.w_head(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = watermark_detected.flatten() SCREAMING_SNAKE_CASE : int = watermark_detected > w_threshold SCREAMING_SNAKE_CASE : Optional[Any] = watermark_detected.tolist() if any(UpperCAmelCase_ ): logger.warning( "Potential watermarked content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, watermark_detected_ in enumerate(UpperCAmelCase_ ): if watermark_detected_: SCREAMING_SNAKE_CASE : List[str] = np.zeros(images[idx].shape ) return images, nsfw_detected, watermark_detected
62
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = 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 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : int ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) 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 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _A ( self : Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9E-2
62
1
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = '''new-model''' if is_tf_available(): class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = NewModelConfig @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Dict = "bert-base-cased" SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = TFAutoModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = "bert-base-cased" SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForPreTraining.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : List[Any] ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = TFAutoModelForCausalLM.from_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForCausalLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : Union[str, Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Dict = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = TFAutoModelForMaskedLM.from_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : Tuple ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Tuple = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : Union[str, Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForQuestionAnswering.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow @require_tensorflow_probability def _A ( self : Optional[int] ): for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: SCREAMING_SNAKE_CASE : int = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForTableQuestionAnswering.from_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = TFAutoModelForTableQuestionAnswering.from_pretrained( UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : List[str] = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase_ ) , 1_4410 ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase_ ) , 1_4410 ) def _A ( self : Optional[Any] ): # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained("sgugger/funnel-random-tiny" ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = copy.deepcopy(model.config ) SCREAMING_SNAKE_CASE : str = ["FunnelBaseModel"] SCREAMING_SNAKE_CASE : List[Any] = TFAutoModel.from_config(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Optional[int] ): try: AutoConfig.register("new-model" , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(UpperCAmelCase_ ): auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ ) auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCAmelCase_ ): auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE : Optional[int] = BertModelTester(self ).get_config() SCREAMING_SNAKE_CASE : Any = NewModelConfig(**tiny_config.to_dict() ) SCREAMING_SNAKE_CASE : Dict = auto_class.from_config(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = auto_class.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def _A ( self : Any ): with self.assertRaisesRegex( UpperCAmelCase_ , "bert-base is not a local folder and is not a valid model identifier" ): SCREAMING_SNAKE_CASE : Dict = TFAutoModel.from_pretrained("bert-base" ) def _A ( self : Optional[int] ): with self.assertRaisesRegex( UpperCAmelCase_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): SCREAMING_SNAKE_CASE : int = TFAutoModel.from_pretrained(UpperCAmelCase_ , revision="aaaaaa" ) def _A ( self : str ): with self.assertRaisesRegex( UpperCAmelCase_ , "hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin" , ): SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModel.from_pretrained("hf-internal-testing/config-no-model" ) def _A ( self : Dict ): with self.assertRaisesRegex(UpperCAmelCase_ , "Use `from_pt=True` to load this model" ): SCREAMING_SNAKE_CASE : str = TFAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only" ) def _A ( self : Optional[int] ): # Make sure we have cached the model. SCREAMING_SNAKE_CASE : str = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE : Dict = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint SCREAMING_SNAKE_CASE : Tuple = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
62
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 ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE : List[Any] = [144, 192, 240] SCREAMING_SNAKE_CASE : Tuple = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [96, 120, 144] SCREAMING_SNAKE_CASE : Dict = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [64, 80, 96] SCREAMING_SNAKE_CASE : List[str] = [16, 16, 24, 48, 64, 80, 320] SCREAMING_SNAKE_CASE : int = 0.05 SCREAMING_SNAKE_CASE : int = 2.0 if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : str = 512 SCREAMING_SNAKE_CASE : List[str] = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 21 SCREAMING_SNAKE_CASE : Dict = "pascal-voc-id2label.json" else: SCREAMING_SNAKE_CASE : Optional[Any] = 1000 SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : Any = "huggingface/label-files" SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowercase , lowercase , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE : List[str] = {int(lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} return config def lowerCamelCase__ ( lowercase , lowercase=False ): """simple docstring""" for i in range(1 , 6 ): if F'''layer_{i}.''' in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(F'''layer_{i}.''' , F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: SCREAMING_SNAKE_CASE : Dict = name.replace("conv_1." , "conv_stem." ) if ".block." in name: SCREAMING_SNAKE_CASE : List[str] = name.replace(".block." , "." ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE : str = name.replace("exp_1x1" , "expand_1x1" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("red_1x1" , "reduce_1x1" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".local_rep.conv_3x3." , ".conv_kxk." ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE : int = name.replace(".local_rep.conv_1x1." , ".conv_1x1." ) if ".norm." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".norm." , ".normalization." ) if ".conv." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".conv." , ".convolution." ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".conv_proj." , ".conv_projection." ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.layer.{j}.''' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.''' ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("expand_1x1" , "downsampling_layer.expand_1x1" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE : str = name.replace("conv_3x3" , "downsampling_layer.conv_3x3" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("reduce_1x1" , "downsampling_layer.reduce_1x1" ) for i in range(2 , 5 ): if F'''.global_rep.{i}.weight''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.global_rep.{i}.weight''' , ".layernorm.weight" ) if F'''.global_rep.{i}.bias''' in name: SCREAMING_SNAKE_CASE : str = name.replace(F'''.global_rep.{i}.bias''' , ".layernorm.bias" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".global_rep." , ".transformer." ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_mha.0." , ".layernorm_before." ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_mha.1.out_proj." , ".attention.output.dense." ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(".pre_norm_ffn.0." , ".layernorm_after." ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_ffn.1." , ".intermediate.dense." ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_ffn.4." , ".output.dense." ) if ".transformer." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".transformer." , ".transformer.layer." ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE : int = name.replace(".aspp_layer." , "." ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".aspp_pool." , "." ) if "seg_head." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("seg_head." , "segmentation_head." ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("segmentation_head.classifier.classifier." , "segmentation_head.classifier." ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("classifier.fc." , "classifier." ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE : List[Any] = "mobilevit." + name return name def lowerCamelCase__ ( lowercase , lowercase , lowercase=False ): """simple docstring""" if base_model: SCREAMING_SNAKE_CASE : Optional[int] = "" else: SCREAMING_SNAKE_CASE : Any = "mobilevit." for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = orig_state_dict.pop(lowercase ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE : int = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.split("." ) SCREAMING_SNAKE_CASE : Any = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE : List[Any] = int(key_split[3] ) SCREAMING_SNAKE_CASE : List[Any] = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) SCREAMING_SNAKE_CASE : int = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE : Union[str, Any] = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: SCREAMING_SNAKE_CASE : str = val[:dim] SCREAMING_SNAKE_CASE : Union[str, Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] else: SCREAMING_SNAKE_CASE : List[Any] = val return orig_state_dict def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_mobilevit_config(lowercase ) # load original state_dict SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(lowercase , map_location="cpu" ) # load 🤗 model if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : List[str] = MobileViTForSemanticSegmentation(lowercase ).eval() else: SCREAMING_SNAKE_CASE : str = MobileViTForImageClassification(lowercase ).eval() SCREAMING_SNAKE_CASE : Any = convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE : List[Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE : List[Any] = model(**lowercase ) SCREAMING_SNAKE_CASE : str = outputs.logits if mobilevit_name.startswith("deeplabv3_" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] , lowercase , atol=1E-4 ) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE : Dict = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] , lowercase , atol=1E-4 ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if push_to_hub: SCREAMING_SNAKE_CASE : List[str] = { "mobilevit_s": "mobilevit-small", "mobilevit_xs": "mobilevit-x-small", "mobilevit_xxs": "mobilevit-xx-small", "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small", "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small", "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small", } print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE : int = model_mapping[mobilevit_name] image_processor.push_to_hub(lowercase , organization="apple" ) model.push_to_hub(lowercase , organization="apple" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, 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 = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
62
1
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = word.split() def justify(lowercase , lowercase , lowercase ) -> str: SCREAMING_SNAKE_CASE : Optional[int] = max_width - width SCREAMING_SNAKE_CASE : List[str] = len(lowercase ) if len(lowercase ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: SCREAMING_SNAKE_CASE : List[Any] = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] SCREAMING_SNAKE_CASE : Optional[Any] = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] SCREAMING_SNAKE_CASE : Tuple = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(lowercase ): num_spaces_between_words_list[i] += 1 SCREAMING_SNAKE_CASE : Any = [] for i in range(lowercase ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(lowercase ) SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : list[str] = [] SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for word in words: if width + len(lowercase ) + len(lowercase ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(lowercase ) width += len(lowercase ) else: # justify the line and add it to result answer.append(justify(lowercase , lowercase , lowercase ) ) # reset new line and new width SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = [word], len(lowercase ) SCREAMING_SNAKE_CASE : Dict = max_width - width - len(lowercase ) answer.append(" ".join(lowercase ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
62
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case = datasets.load_iris() snake_case = np.array(data["""data"""]) snake_case = np.array(data["""target"""]) snake_case = data["""target_names"""] snake_case , snake_case , snake_case , snake_case = train_test_split(X, y) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase=5 ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = zip(lowercase , lowercase ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE : Optional[int] = [] for data_point in data: SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE : List[Any] = [i[1] for i in sorted(lowercase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE : List[Any] = Counter(lowercase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
62
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """huggingface/informer-tourism-monthly""": ( """https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json""" ), # See all Informer models at https://huggingface.co/models?filter=informer } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''informer''' UpperCamelCase_ : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Any , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = "student_t" , UpperCAmelCase_ : str = "nll" , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : List[int] = None , UpperCAmelCase_ : Optional[Union[str, bool]] = "mean" , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : int = 64 , UpperCAmelCase_ : int = 32 , UpperCAmelCase_ : int = 32 , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : str = "gelu" , UpperCAmelCase_ : float = 0.05 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : int = 100 , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str = "prob" , UpperCAmelCase_ : int = 5 , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Tuple , ): # time series specific configuration SCREAMING_SNAKE_CASE : str = prediction_length SCREAMING_SNAKE_CASE : List[str] = context_length or prediction_length SCREAMING_SNAKE_CASE : Optional[Any] = distribution_output SCREAMING_SNAKE_CASE : Tuple = loss SCREAMING_SNAKE_CASE : List[Any] = input_size SCREAMING_SNAKE_CASE : Any = num_time_features SCREAMING_SNAKE_CASE : List[str] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] SCREAMING_SNAKE_CASE : List[Any] = scaling SCREAMING_SNAKE_CASE : List[Any] = num_dynamic_real_features SCREAMING_SNAKE_CASE : Dict = num_static_real_features SCREAMING_SNAKE_CASE : Dict = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(UpperCAmelCase_ ) != num_static_categorical_features: raise ValueError( "The cardinality should be a list of the same length as `num_static_categorical_features`" ) SCREAMING_SNAKE_CASE : Any = cardinality else: SCREAMING_SNAKE_CASE : Optional[int] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(UpperCAmelCase_ ) != num_static_categorical_features: raise ValueError( "The embedding dimension should be a list of the same length as `num_static_categorical_features`" ) SCREAMING_SNAKE_CASE : Tuple = embedding_dimension else: SCREAMING_SNAKE_CASE : List[str] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] SCREAMING_SNAKE_CASE : Optional[Any] = num_parallel_samples # Transformer architecture configuration SCREAMING_SNAKE_CASE : List[Any] = input_size * len(self.lags_sequence ) + self._number_of_features SCREAMING_SNAKE_CASE : Dict = d_model SCREAMING_SNAKE_CASE : List[str] = encoder_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = decoder_attention_heads SCREAMING_SNAKE_CASE : str = encoder_ffn_dim SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = encoder_layers SCREAMING_SNAKE_CASE : Optional[Any] = decoder_layers SCREAMING_SNAKE_CASE : List[str] = dropout SCREAMING_SNAKE_CASE : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE : Dict = activation_dropout SCREAMING_SNAKE_CASE : List[str] = encoder_layerdrop SCREAMING_SNAKE_CASE : Tuple = decoder_layerdrop SCREAMING_SNAKE_CASE : str = activation_function SCREAMING_SNAKE_CASE : Union[str, Any] = init_std SCREAMING_SNAKE_CASE : Any = use_cache # Informer SCREAMING_SNAKE_CASE : Dict = attention_type SCREAMING_SNAKE_CASE : Dict = sampling_factor SCREAMING_SNAKE_CASE : Any = distil super().__init__(is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_ ) @property def _A ( self : Any ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
62
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''xlm-prophetnet''' UpperCamelCase_ : Tuple = ['''past_key_values'''] UpperCamelCase_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Dict , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[Union[str, Callable]] = "gelu" , UpperCAmelCase_ : Optional[int] = 3_0522 , UpperCAmelCase_ : Optional[int] = 1024 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[int] = 512 , UpperCAmelCase_ : Optional[float] = 0.02 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 2 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 128 , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[float] = 0.0 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 2 , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = num_encoder_layers SCREAMING_SNAKE_CASE : Any = num_encoder_attention_heads SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers SCREAMING_SNAKE_CASE : List[Any] = num_decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE : Dict = ngram SCREAMING_SNAKE_CASE : Any = num_buckets SCREAMING_SNAKE_CASE : str = relative_max_distance SCREAMING_SNAKE_CASE : str = disable_ngram_loss SCREAMING_SNAKE_CASE : Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : int = use_cache super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , add_cross_attention=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def _A ( self : int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
62
1
def lowerCamelCase__ ( lowercase = 1000000 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : Union[str, Any] = 1 SCREAMING_SNAKE_CASE : Optional[int] = {1: 1} for inputa in range(2 , lowercase ): SCREAMING_SNAKE_CASE : List[str] = 0 SCREAMING_SNAKE_CASE : List[str] = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: SCREAMING_SNAKE_CASE : Tuple = (3 * number) + 1 counter += 1 if inputa not in counters: SCREAMING_SNAKE_CASE : Optional[Any] = counter if counter > pre_counter: SCREAMING_SNAKE_CASE : str = inputa SCREAMING_SNAKE_CASE : Tuple = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
62
import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, 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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = KandinskyVaaPipeline UpperCamelCase_ : List[Any] = [ '''image_embeds''', '''negative_image_embeds''', ] UpperCamelCase_ : Tuple = ['''image_embeds''', '''negative_image_embeds'''] UpperCamelCase_ : Any = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCamelCase_ : List[str] = False @property def _A ( self : List[Any] ): return 32 @property def _A ( self : List[Any] ): return 32 @property def _A ( self : Any ): return self.time_input_dim @property def _A ( self : Union[str, Any] ): return self.time_input_dim * 4 @property def _A ( self : Tuple ): return 100 @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } SCREAMING_SNAKE_CASE : str = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def _A ( self : int ): 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 : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = self.dummy_unet SCREAMING_SNAKE_CASE : str = self.dummy_movq SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="epsilon" , thresholding=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _A ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]=0 ): SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = "cpu" SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : Tuple = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array( [0.6_237_976, 1.0, 0.36_441_332, 1.0, 0.70_639_634, 0.29_877_186, 0.85_652_125, 0.5_216_843, 0.54_454_046] ) 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy" ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Tuple = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = "red cat, 4k photo" SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="np" , ) SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
62
1
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""} # See all LED models at https://huggingface.co/models?filter=LED snake_case = { """vocab_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""", }, """merges_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""", }, """tokenizer_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""", }, } snake_case = { """allenai/led-base-16384""": 16_384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = bs[:] SCREAMING_SNAKE_CASE : Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(lowercase ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE : Union[str, Any] = [chr(lowercase ) for n in cs] return dict(zip(lowercase , lowercase ) ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = set() SCREAMING_SNAKE_CASE : Optional[int] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE : Optional[int] = char return pairs class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Dict = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Dict="replace" , UpperCAmelCase_ : Tuple="<s>" , UpperCAmelCase_ : Optional[int]="</s>" , UpperCAmelCase_ : List[str]="</s>" , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : List[str]="<unk>" , UpperCAmelCase_ : Dict="<pad>" , UpperCAmelCase_ : str="<mask>" , UpperCAmelCase_ : Dict=False , **UpperCAmelCase_ : Union[str, Any] , ): SCREAMING_SNAKE_CASE : Optional[int] = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else bos_token SCREAMING_SNAKE_CASE : List[Any] = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else eos_token SCREAMING_SNAKE_CASE : int = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else sep_token SCREAMING_SNAKE_CASE : Any = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else cls_token SCREAMING_SNAKE_CASE : Tuple = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else unk_token SCREAMING_SNAKE_CASE : int = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : List[str] = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token super().__init__( errors=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , **UpperCAmelCase_ , ) with open(UpperCAmelCase_ , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE : List[str] = json.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE : List[str] = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE : Optional[int] = bytes_to_unicode() SCREAMING_SNAKE_CASE : str = {v: k for k, v in self.byte_encoder.items()} with open(UpperCAmelCase_ , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE : str = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE : Tuple = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE : Dict = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Dict = {} SCREAMING_SNAKE_CASE : Optional[int] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def _A ( self : List[Any] ): return len(self.encoder ) def _A ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def _A ( self : str , UpperCAmelCase_ : Dict ): if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE : Optional[int] = tuple(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = get_pairs(UpperCAmelCase_ ) if not pairs: return token while True: SCREAMING_SNAKE_CASE : Union[str, Any] = min(UpperCAmelCase_ , key=lambda UpperCAmelCase_ : self.bpe_ranks.get(UpperCAmelCase_ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = bigram SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Optional[Any] = 0 while i < len(UpperCAmelCase_ ): try: SCREAMING_SNAKE_CASE : List[Any] = word.index(UpperCAmelCase_ , UpperCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE : str = j if word[i] == first and i < len(UpperCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE : Union[str, Any] = tuple(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = new_word if len(UpperCAmelCase_ ) == 1: break else: SCREAMING_SNAKE_CASE : Tuple = get_pairs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = " ".join(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = word return word def _A ( self : str , UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : List[Any] = [] for token in re.findall(self.pat , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Any = "".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(UpperCAmelCase_ ).split(" " ) ) return bpe_tokens def _A ( self : List[Any] , UpperCAmelCase_ : int ): return self.encoder.get(UpperCAmelCase_ , self.encoder.get(self.unk_token ) ) def _A ( self : str , UpperCAmelCase_ : int ): return self.decoder.get(UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = "".join(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): if not os.path.isdir(UpperCAmelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Dict = os.path.join( UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : str = os.path.join( UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCAmelCase_ , ensure_ascii=UpperCAmelCase_ ) + "\n" ) SCREAMING_SNAKE_CASE : Any = 0 with open(UpperCAmelCase_ , "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 UpperCAmelCase_ : 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!" ) SCREAMING_SNAKE_CASE : List[Any] = token_index writer.write(" ".join(UpperCAmelCase_ ) + "\n" ) index += 1 return vocab_file, merge_file def _A ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : Optional[int] = [self.cls_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _A ( self : Optional[Any] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1, 1] + ([0] * len(UpperCAmelCase_ )) + [1] def _A ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : int = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [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 _A ( self : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int=False , **UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(UpperCAmelCase_ ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE : Any = " " + text return (text, kwargs) def _A ( self : int , UpperCAmelCase_ : Union[Dict[str, EncodedInput], BatchEncoding] , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , ): SCREAMING_SNAKE_CASE : int = super()._pad( encoded_inputs=UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding_strategy=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , ) # Load from model defaults if return_attention_mask is None: SCREAMING_SNAKE_CASE : List[Any] = "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: SCREAMING_SNAKE_CASE : Optional[Any] = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. SCREAMING_SNAKE_CASE : Dict = len(encoded_inputs["global_attention_mask"] ) != len(UpperCAmelCase_ ) if needs_to_be_padded: SCREAMING_SNAKE_CASE : int = len(UpperCAmelCase_ ) - len(encoded_inputs["global_attention_mask"] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` SCREAMING_SNAKE_CASE : Any = ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": SCREAMING_SNAKE_CASE : List[Any] = [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return encoded_inputs
62
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput snake_case = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : int , *UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Tuple=None , **UpperCAmelCase_ : Optional[Any] ): super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = eval_examples SCREAMING_SNAKE_CASE : List[Any] = post_process_function SCREAMING_SNAKE_CASE : Any = quant_trainer_args SCREAMING_SNAKE_CASE : Optional[Any] = 128 # default number of calibration samples def _A ( self : Optional[Any] , UpperCAmelCase_ : Tuple=None ): if calib_dataset is None and self.calib_dataset is None: raise ValueError("Trainer: calibration requires an calib_dataset." ) SCREAMING_SNAKE_CASE : str = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE : str = self._remove_unused_columns(UpperCAmelCase_ , description="Calibration" ) return DataLoader( UpperCAmelCase_ , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=UpperCAmelCase_ , ) def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[int]=None ): SCREAMING_SNAKE_CASE : Any = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_calib_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args , calib=UpperCAmelCase_ ) model.eval() quant_trainer.enable_calibration(UpperCAmelCase_ ) logger.info("***** Running calibration *****" ) logger.info(f''' Num examples = {self.calib_num}''' ) logger.info(f''' Batch size = {calib_dataloader.batch_size}''' ) for step, inputs in enumerate(UpperCAmelCase_ ): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.prediction_step(UpperCAmelCase_ , UpperCAmelCase_ , prediction_loss_only=UpperCAmelCase_ ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : Optional[int] = model def _A ( self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str = "eval" ): SCREAMING_SNAKE_CASE : List[str] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : Tuple = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : int = eval_loop( UpperCAmelCase_ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : int = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE : List[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions ) SCREAMING_SNAKE_CASE : Any = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = metrics.pop(UpperCAmelCase_ ) self.log(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : List[Any] = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : List[str] = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCAmelCase_ ) return metrics def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : str = "test" ): SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(UpperCAmelCase_ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Tuple = self.compute_metrics SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : str = eval_loop( UpperCAmelCase_ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : Union[str, Any] = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Optional[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions , "predict" ) SCREAMING_SNAKE_CASE : str = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : str = metrics.pop(UpperCAmelCase_ ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCAmelCase_ ) def _A ( self : Any , UpperCAmelCase_ : int="./" ): SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = next(iter(UpperCAmelCase_ ) ) # saving device - to make it consistent SCREAMING_SNAKE_CASE : int = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) # convert to tuple SCREAMING_SNAKE_CASE : Tuple = tuple(v.to(UpperCAmelCase_ ) for k, v in batch.items() ) logger.info("Converting model to be onnx compatible" ) from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Any = self.model.to(UpperCAmelCase_ ) model.eval() model.float() SCREAMING_SNAKE_CASE : str = model.module if hasattr(UpperCAmelCase_ , "module" ) else model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : List[Any] = os.path.join(UpperCAmelCase_ , "model.onnx" ) logger.info(f'''exporting model to {output_model_file}''' ) SCREAMING_SNAKE_CASE : int = {0: "batch_size", 1: "seq_len"} torch.onnx.export( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , export_params=UpperCAmelCase_ , opset_version=13 , do_constant_folding=UpperCAmelCase_ , input_names=["input_ids", "attention_mask", "token_type_ids"] , output_names=["output_start_logits", "output_end_logits"] , dynamic_axes={ "input_ids": axes, "attention_mask": axes, "token_type_ids": axes, "output_start_logits": axes, "output_end_logits": axes, } , verbose=UpperCAmelCase_ , ) logger.info("onnx export finished" )
62
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 ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : str = IFPipeline UpperCamelCase_ : Union[str, Any] = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} UpperCamelCase_ : Optional[int] = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase_ : int = PipelineTesterMixin.required_optional_params - {'''latents'''} def _A ( self : int ): return self._get_dummy_components() def _A ( self : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str]=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def _A ( self : Optional[int] ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def _A ( self : str ): # 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 _A ( self : Optional[int] ): self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _A ( self : Optional[int] ): self._test_save_load_local() def _A ( self : List[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 _A ( self : Any ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : str ): # if SCREAMING_SNAKE_CASE : int = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0" , variant="fp16" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : int = 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" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = pipe_a.encode_prompt("anime turtle" , device="cuda" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : List[Any] = 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 SCREAMING_SNAKE_CASE : Dict = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Any = 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 SCREAMING_SNAKE_CASE : Tuple = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE : Dict = 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 _A ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str ): # pipeline 1 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , num_inference_steps=2 , generator=UpperCAmelCase_ , output_type="np" , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 SCREAMING_SNAKE_CASE : Any = 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() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=2 , output_type="np" , ) SCREAMING_SNAKE_CASE : Any = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : str = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : List[str] = 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 _A ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ): # pipeline 1 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , num_inference_steps=2 , generator=UpperCAmelCase_ , output_type="np" , ) SCREAMING_SNAKE_CASE : List[str] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : List[Any] = 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() SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , original_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=2 , output_type="np" , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : str = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] ): # pipeline 1 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , mask_image=UpperCAmelCase_ , num_inference_steps=2 , generator=UpperCAmelCase_ , output_type="np" , ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE : Optional[int] = 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() SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = 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" , ) SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (256, 256, 3) SCREAMING_SNAKE_CASE : str = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE : Tuple = 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__ ( ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
62
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = LayoutLMTokenizer UpperCamelCase_ : str = LayoutLMTokenizerFast UpperCamelCase_ : Any = True UpperCamelCase_ : Optional[Any] = True def _A ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : str , **UpperCAmelCase_ : Optional[int] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Any = "UNwant\u00E9d,running" SCREAMING_SNAKE_CASE : Union[str, Any] = "unwanted, running" return input_text, output_text def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [7, 4, 5, 10, 8, 9] ) def _A ( self : List[str] ): pass
62
1
import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = MODEL_FOR_CAUSAL_LM_MAPPING UpperCamelCase_ : Optional[int] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="pt" ) # Using `do_sample=False` to force deterministic output SCREAMING_SNAKE_CASE : List[Any] = text_generator("This is a test" , do_sample=UpperCAmelCase_ ) self.assertEqual( UpperCAmelCase_ , [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ] , ) SCREAMING_SNAKE_CASE : str = text_generator(["This is a test", "This is a second test"] ) self.assertEqual( UpperCAmelCase_ , [ [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ], [ { "generated_text": ( "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy" " oscope. oscope. FiliFili@@" ) } ], ] , ) SCREAMING_SNAKE_CASE : str = text_generator("This is a test" , do_sample=UpperCAmelCase_ , num_return_sequences=2 , return_tensors=UpperCAmelCase_ ) self.assertEqual( UpperCAmelCase_ , [ {"generated_token_ids": ANY(UpperCAmelCase_ )}, {"generated_token_ids": ANY(UpperCAmelCase_ )}, ] , ) SCREAMING_SNAKE_CASE : List[Any] = text_generator.model.config.eos_token_id SCREAMING_SNAKE_CASE : Union[str, Any] = "<pad>" SCREAMING_SNAKE_CASE : List[str] = text_generator( ["This is a test", "This is a second test"] , do_sample=UpperCAmelCase_ , num_return_sequences=2 , batch_size=2 , return_tensors=UpperCAmelCase_ , ) self.assertEqual( UpperCAmelCase_ , [ [ {"generated_token_ids": ANY(UpperCAmelCase_ )}, {"generated_token_ids": ANY(UpperCAmelCase_ )}, ], [ {"generated_token_ids": ANY(UpperCAmelCase_ )}, {"generated_token_ids": ANY(UpperCAmelCase_ )}, ], ] , ) @require_tf def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : str = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="tf" ) # Using `do_sample=False` to force deterministic output SCREAMING_SNAKE_CASE : str = text_generator("This is a test" , do_sample=UpperCAmelCase_ ) self.assertEqual( UpperCAmelCase_ , [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ] , ) SCREAMING_SNAKE_CASE : Optional[int] = text_generator(["This is a test", "This is a second test"] , do_sample=UpperCAmelCase_ ) self.assertEqual( UpperCAmelCase_ , [ [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ], [ { "generated_text": ( "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes" " Cannes 閲閲Cannes Cannes Cannes 攵 please," ) } ], ] , ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : List[str] = TextGenerationPipeline(model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ ) return text_generator, ["This is a test", "Another test"] def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = "Hello I believe in" SCREAMING_SNAKE_CASE : int = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : Optional[Any] = text_generator(UpperCAmelCase_ ) self.assertEqual( UpperCAmelCase_ , [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}] , ) SCREAMING_SNAKE_CASE : Dict = text_generator(UpperCAmelCase_ , stop_sequence=" fe" ) self.assertEqual(UpperCAmelCase_ , [{"generated_text": "Hello I believe in fe"}] ) def _A ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[Any] = text_generator.model SCREAMING_SNAKE_CASE : Union[str, Any] = text_generator.tokenizer SCREAMING_SNAKE_CASE : str = text_generator("This is a test" ) self.assertEqual(UpperCAmelCase_ , [{"generated_text": ANY(UpperCAmelCase_ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) SCREAMING_SNAKE_CASE : Optional[int] = text_generator("This is a test" , return_full_text=UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , [{"generated_text": ANY(UpperCAmelCase_ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) SCREAMING_SNAKE_CASE : Optional[int] = pipeline(task="text-generation" , model=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , return_full_text=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = text_generator("This is a test" ) self.assertEqual(UpperCAmelCase_ , [{"generated_text": ANY(UpperCAmelCase_ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) SCREAMING_SNAKE_CASE : List[str] = text_generator("This is a test" , return_full_text=UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , [{"generated_text": ANY(UpperCAmelCase_ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) SCREAMING_SNAKE_CASE : int = text_generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=UpperCAmelCase_ ) self.assertEqual( UpperCAmelCase_ , [ [{"generated_text": ANY(UpperCAmelCase_ )}, {"generated_text": ANY(UpperCAmelCase_ )}], [{"generated_text": ANY(UpperCAmelCase_ )}, {"generated_text": ANY(UpperCAmelCase_ )}], ] , ) if text_generator.tokenizer.pad_token is not None: SCREAMING_SNAKE_CASE : List[Any] = text_generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=UpperCAmelCase_ ) self.assertEqual( UpperCAmelCase_ , [ [{"generated_text": ANY(UpperCAmelCase_ )}, {"generated_text": ANY(UpperCAmelCase_ )}], [{"generated_text": ANY(UpperCAmelCase_ )}, {"generated_text": ANY(UpperCAmelCase_ )}], ] , ) with self.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Dict = text_generator("test" , return_full_text=UpperCAmelCase_ , return_text=UpperCAmelCase_ ) with self.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = text_generator("test" , return_full_text=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) with self.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = text_generator("test" , return_text=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): SCREAMING_SNAKE_CASE : Tuple = text_generator("" ) self.assertEqual(UpperCAmelCase_ , [{"generated_text": ANY(UpperCAmelCase_ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): SCREAMING_SNAKE_CASE : Union[str, Any] = text_generator("" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. SCREAMING_SNAKE_CASE : Tuple = ["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"] if ( tokenizer.model_max_length < 1_0000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("This is a test" * 500 , max_new_tokens=20 ) SCREAMING_SNAKE_CASE : Optional[Any] = text_generator("This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(UpperCAmelCase_ ): text_generator( "This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def _A ( self : Union[str, Any] ): import torch # Classic `model_kwargs` SCREAMING_SNAKE_CASE : List[str] = pipeline( model="hf-internal-testing/tiny-random-bloom" , model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) SCREAMING_SNAKE_CASE : List[str] = pipe("This is a test" ) self.assertEqual( UpperCAmelCase_ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) SCREAMING_SNAKE_CASE : Tuple = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) SCREAMING_SNAKE_CASE : str = pipe("This is a test" ) self.assertEqual( UpperCAmelCase_ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 SCREAMING_SNAKE_CASE : int = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) SCREAMING_SNAKE_CASE : List[Any] = pipe("This is a test" ) self.assertEqual( UpperCAmelCase_ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) @require_torch @require_torch_gpu def _A ( self : Optional[Any] ): import torch SCREAMING_SNAKE_CASE : Dict = pipeline(model="hf-internal-testing/tiny-random-bloom" , device=0 , torch_dtype=torch.floataa ) pipe("This is a test" ) @require_torch @require_accelerate @require_torch_gpu def _A ( self : List[str] ): import torch SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.floataa ) pipe("This is a test" , do_sample=UpperCAmelCase_ , top_p=0.5 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Optional[Any] = "Hello world" SCREAMING_SNAKE_CASE : List[Any] = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) if text_generator.model.framework == "tf": SCREAMING_SNAKE_CASE : str = logging.get_logger("transformers.generation.tf_utils" ) else: SCREAMING_SNAKE_CASE : int = logging.get_logger("transformers.generation.utils" ) SCREAMING_SNAKE_CASE : List[str] = "Both `max_new_tokens`" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(UpperCAmelCase_ ) as cl: SCREAMING_SNAKE_CASE : int = text_generator(UpperCAmelCase_ , max_length=10 , max_new_tokens=1 ) self.assertIn(UpperCAmelCase_ , cl.out ) # The user only sets one -> no warning with CaptureLogger(UpperCAmelCase_ ) as cl: SCREAMING_SNAKE_CASE : Optional[Any] = text_generator(UpperCAmelCase_ , max_new_tokens=1 ) self.assertNotIn(UpperCAmelCase_ , cl.out ) with CaptureLogger(UpperCAmelCase_ ) as cl: SCREAMING_SNAKE_CASE : Optional[Any] = text_generator(UpperCAmelCase_ , max_length=10 ) self.assertNotIn(UpperCAmelCase_ , cl.out )
62
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = os.path.join(args.tf_model_dir , "parameters.json" ) SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(open(lowercase ).read() ) if not params: raise ValueError( F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.''' ) if not args.output.endswith(".pt" ): SCREAMING_SNAKE_CASE : Optional[int] = args.output + ".pt" SCREAMING_SNAKE_CASE : Any = OrderedDict() with tf.device("/CPU:0" ): SCREAMING_SNAKE_CASE : Union[str, Any] = tf.train.load_checkpoint(args.tf_model_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): SCREAMING_SNAKE_CASE : Any = reader.get_tensor(lowercase ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9] ) elif key_name.startswith("pasts/out" ): SCREAMING_SNAKE_CASE : Optional[int] = 8 SCREAMING_SNAKE_CASE : List[Any] = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time SCREAMING_SNAKE_CASE : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.startswith("model/moe" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/softmlp/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): SCREAMING_SNAKE_CASE : Optional[int] = key_name[-9:-7] for i in range(16 ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) SCREAMING_SNAKE_CASE : List[str] = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name.startswith("model/mlp" ): SCREAMING_SNAKE_CASE : str = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.mlp.wi.weight" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/p1/bias" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.wi.bias" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/kernel" ): SCREAMING_SNAKE_CASE : str = "model.blocks.%d.feed_forward.mlp.wo.weight" % player SCREAMING_SNAKE_CASE : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/bias" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.feed_forward.mlp.wo.bias" % player SCREAMING_SNAKE_CASE : str = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) elif key_name.startswith("model/ln" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.norm.bias" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : List[str] = "model.blocks.%d.feed_forward.norm.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/att" ): SCREAMING_SNAKE_CASE : Optional[int] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum SCREAMING_SNAKE_CASE : List[str] = state[:, 0, :, :] SCREAMING_SNAKE_CASE : Tuple = state[:, 1, :, :] SCREAMING_SNAKE_CASE : List[Any] = state[:, 2, :, :] SCREAMING_SNAKE_CASE : Tuple = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : int = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/o/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif key_name.startswith("model/an" ): SCREAMING_SNAKE_CASE : int = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.self_attn.norm.bias" % player SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.self_attn.norm.weight" % player SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): SCREAMING_SNAKE_CASE : str = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] SCREAMING_SNAKE_CASE : List[str] = "model.%s.weight" % nlayer SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) if key_name.startswith("model/wte" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "lm_head.weight" SCREAMING_SNAKE_CASE : List[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/wob" ): SCREAMING_SNAKE_CASE : List[Any] = "final_logits_bias" SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : List[str] = state.reshape((1, -1) ) SCREAMING_SNAKE_CASE : int = torch.tensor(lowercase ) elif key_name == "model/dense/kernel": SCREAMING_SNAKE_CASE : Optional[int] = "model.last_project.weight" SCREAMING_SNAKE_CASE : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name == "model/dense_1/bias": SCREAMING_SNAKE_CASE : str = "model.last_project.bias" SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) torch.save(lowercase , args.output ) if __name__ == "__main__": snake_case = argparse.ArgumentParser( description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""") parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""") snake_case = parser.parse_args() convert_tf_gptsan_to_pt(args)
62
1
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) snake_case = logging.getLogger() snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] , UpperCAmelCase_ : int ): os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = {"source": "What is love ?", "target": "life"} SCREAMING_SNAKE_CASE : Tuple = {"train": 12, "val": 2, "test": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: SCREAMING_SNAKE_CASE : Dict = "\n".join([contents[field]] * n_lines[split] ) with open(os.path.join(UpperCAmelCase_ , f'''{split}.{field}''' ) , "w" ) as f: f.write(UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : str = "pytorch" ): SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = os.path.join(UpperCAmelCase_ , "output" ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(UpperCAmelCase_ , "data" ) self._create_dummy_data(data_dir=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = f''' --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''' ) if is_apex_available(): testargs.append("--fp16" ) else: testargs.append("--gpus=0" ) testargs.append("--distributed_backend=ddp_cpu" ) testargs.append("--num_processes=2" ) SCREAMING_SNAKE_CASE : Any = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) SCREAMING_SNAKE_CASE : List[str] = os.path.join(UpperCAmelCase_ , "metrics.json" ) with open(UpperCAmelCase_ ) as f: SCREAMING_SNAKE_CASE : Dict = json.load(UpperCAmelCase_ ) return result @require_torch_gpu def _A ( self : int ): SCREAMING_SNAKE_CASE : Union[str, Any] = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_gpu @require_ray def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu @require_ray def _A ( self : int ): SCREAMING_SNAKE_CASE : int = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 )
62
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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: on SCREAMING_SNAKE_CASE : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Optional[int] = { "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], } SCREAMING_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 _A ( self : List[Any] , **UpperCAmelCase_ : List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Union[str, Any] , **UpperCAmelCase_ : Any ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Union[str, Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE : Any = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) SCREAMING_SNAKE_CASE : str = 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 _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : int = image_processor(UpperCAmelCase_ , return_tensors="np" ) SCREAMING_SNAKE_CASE : Optional[int] = 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 _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = "lower newer" SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : int = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = "lower newer" SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Optional[Any] = processor.batch_decode(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = "lower newer" SCREAMING_SNAKE_CASE : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
62
1
import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = AlbertConfig.from_json_file(lowercase ) print(F'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE : Optional[int] = AlbertForPreTraining(lowercase ) # Load weights from tf checkpoint load_tf_weights_in_albert(lowercase , lowercase , lowercase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase ) if __name__ == "__main__": snake_case = 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( """--albert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained ALBERT 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.""" ) snake_case = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
62
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "tf_padding" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "depth_multiplier" ) ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]=13 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : int=0.25 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : Dict=8 , UpperCAmelCase_ : Optional[int]=6 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : str="relu6" , UpperCAmelCase_ : List[str]=1280 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : int = depth_multiplier SCREAMING_SNAKE_CASE : str = depth_divisible_by SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth SCREAMING_SNAKE_CASE : int = expand_ratio SCREAMING_SNAKE_CASE : Tuple = tf_padding SCREAMING_SNAKE_CASE : List[str] = output_stride SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion SCREAMING_SNAKE_CASE : Any = finegrained_output SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = scope def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels, pixel_labels def _A ( self : Optional[int] ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Dict = MobileNetVaForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase_ : List[Any] = ( { '''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification, '''image-segmentation''': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Any = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : int = False UpperCamelCase_ : str = False def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def _A ( self : List[Any] ): pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def _A ( self : Dict ): pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def _A ( self : Union[str, Any] ): pass def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): def check_hidden_states_output(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 16 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : str = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def _A ( self : Optional[Any] ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : int = MobileNetVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Optional[int] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ ) # verify the logits SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : int = model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.tensor( [ [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]], [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]], [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
62
1
import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Any = 8 # DPR tok SCREAMING_SNAKE_CASE : str = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , "dpr_tokenizer" ) os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(UpperCAmelCase_ , DPR_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] ) ) # BART tok SCREAMING_SNAKE_CASE : List[str] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] SCREAMING_SNAKE_CASE : Tuple = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Optional[Any] = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] SCREAMING_SNAKE_CASE : Tuple = {"unk_token": "<unk>"} SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , "bart_tokenizer" ) os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(UpperCAmelCase_ , BART_VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : str = os.path.join(UpperCAmelCase_ , BART_VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : Union[str, Any] ): return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def _A ( self : Tuple ): return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer" ) ) def _A ( self : Tuple ): return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , "bart_tokenizer" ) ) def _A ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def _A ( self : int ): SCREAMING_SNAKE_CASE : str = Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_dataset() SCREAMING_SNAKE_CASE : Optional[Any] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: SCREAMING_SNAKE_CASE : List[Any] = dataset SCREAMING_SNAKE_CASE : int = RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def _A ( self : List[Any] , UpperCAmelCase_ : bool ): SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_dataset() SCREAMING_SNAKE_CASE : Optional[int] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="custom" , ) if from_disk: SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , "dataset" ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , "index.faiss" ) dataset.get_index("embeddings" ).save(os.path.join(self.tmpdirname , "index.faiss" ) ) dataset.drop_index("embeddings" ) dataset.save_to_disk(os.path.join(self.tmpdirname , "dataset" ) ) del dataset SCREAMING_SNAKE_CASE : Tuple = RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , UpperCAmelCase_ ) , ) return retriever def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Optional[int] = Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , "hf_bert_base.hnswSQ8_correct_phi_128.c_index" ) dataset.save_faiss_index("embeddings" , index_file_name + ".index.dpr" ) pickle.dump(dataset["id"] , open(index_file_name + ".index_meta.dpr" , "wb" ) ) SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , "psgs_w100.tsv.pkl" ) SCREAMING_SNAKE_CASE : Union[str, Any] = {sample["id"]: [sample["text"], sample["title"]] for sample in dataset} pickle.dump(UpperCAmelCase_ , open(UpperCAmelCase_ , "wb" ) ) SCREAMING_SNAKE_CASE : Optional[int] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="legacy" , index_path=self.tmpdirname , ) SCREAMING_SNAKE_CASE : Dict = RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : str = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , UpperCAmelCase_ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : int = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("transformers.models.rag.retrieval_rag.load_dataset" ) as mock_load_dataset: SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_dataset() retriever.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = RagRetriever.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE : List[str] = retriever.retrieve(UpperCAmelCase_ , n_docs=1 ) self.assertTrue(out is not None ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , UpperCAmelCase_ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = RagRetriever.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE : Optional[Any] = retriever.retrieve(UpperCAmelCase_ , n_docs=1 ) self.assertTrue(out is not None ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["embeddings", "id", "text", "title"] ) self.assertEqual(len(doc_dicts[0]["id"] ) , UpperCAmelCase_ ) self.assertEqual(doc_dicts[0]["id"][0] , "1" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = RagRetriever.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE : Union[str, Any] = retriever.retrieve(UpperCAmelCase_ , n_docs=1 ) self.assertTrue(out is not None ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_legacy_index_retriever() SCREAMING_SNAKE_CASE : Optional[int] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(UpperCAmelCase_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["text", "title"] ) self.assertEqual(len(doc_dicts[0]["text"] ) , UpperCAmelCase_ ) self.assertEqual(doc_dicts[0]["text"][0] , "bar" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["text"][0] , "foo" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = RagRetriever.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE : Union[str, Any] = retriever.retrieve(UpperCAmelCase_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _A ( self : List[Any] ): import torch SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE : Tuple = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE : Tuple = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE : str = retriever(UpperCAmelCase_ , UpperCAmelCase_ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = ( out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) SCREAMING_SNAKE_CASE : Union[str, Any] = retriever( UpperCAmelCase_ , UpperCAmelCase_ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase_ , return_tensors="pt" , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = ( # noqa: F841 out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], out["doc_ids"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = self.get_dpr_ctx_encoder_tokenizer() SCREAMING_SNAKE_CASE : str = 1 SCREAMING_SNAKE_CASE : str = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_ ) retriever.set_ctx_encoder_tokenizer(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE : str = retriever(UpperCAmelCase_ , UpperCAmelCase_ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase_ ) self.assertEqual( len(UpperCAmelCase_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask") ) , UpperCAmelCase_ ) # check for doc token related keys in dictionary.
62
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" def constraint_to_multiple_of(lowercase , lowercase , lowercase=0 , lowercase=None ): SCREAMING_SNAKE_CASE : Any = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : int = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Tuple = (output_size, output_size) if isinstance(lowercase , lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_image_size(lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Tuple = output_height / input_height SCREAMING_SNAKE_CASE : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width SCREAMING_SNAKE_CASE : List[str] = scale_width else: # fit height SCREAMING_SNAKE_CASE : Optional[Any] = scale_height SCREAMING_SNAKE_CASE : int = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase ) SCREAMING_SNAKE_CASE : Dict = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase ) return (new_height, new_width) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase_ : str , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = size if size is not None else {"height": 384, "width": 384} SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : int = ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample SCREAMING_SNAKE_CASE : List[str] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self : Tuple , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : int , ): SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = get_resize_output_image_size( UpperCAmelCase_ , output_size=(size["height"], size["width"]) , keep_aspect_ratio=UpperCAmelCase_ , multiple=UpperCAmelCase_ , ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Dict , ): return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ): return normalize(UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : Optional[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : List[str] = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Any = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Tuple = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Tuple = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Tuple] = None ): SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : str = [] for idx in range(len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
62
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int=7 , UpperCAmelCase_ : Optional[Any]=3 , UpperCAmelCase_ : Any=18 , UpperCAmelCase_ : Tuple=30 , UpperCAmelCase_ : Optional[Any]=400 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase_ : Dict=[0.5, 0.5, 0.5] , ): SCREAMING_SNAKE_CASE : Union[str, Any] = size if size is not None else {"shortest_edge": 18} SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : List[Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = num_channels SCREAMING_SNAKE_CASE : Tuple = image_size SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution SCREAMING_SNAKE_CASE : str = do_resize SCREAMING_SNAKE_CASE : List[str] = size SCREAMING_SNAKE_CASE : Any = do_center_crop SCREAMING_SNAKE_CASE : Tuple = crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean SCREAMING_SNAKE_CASE : Tuple = image_std def _A ( self : Union[str, Any] ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = LevitImageProcessor if is_vision_available() else None def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Dict = LevitImageProcessingTester(self ) @property def _A ( self : Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , "image_mean" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "image_std" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_normalize" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_resize" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_center_crop" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "size" ) ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE : Optional[int] = 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 _A ( self : Tuple ): pass def _A ( self : Any ): # Initialize image_processing SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[str] = image_processing(UpperCAmelCase_ , 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 _A ( self : Union[str, Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Tuple = image_processing(UpperCAmelCase_ , 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 _A ( self : str ): # Initialize image_processing SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = image_processing(UpperCAmelCase_ , 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"], ) , )
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : int = 6 ): SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None self.create_linked_list(UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Optional[int] = Node() SCREAMING_SNAKE_CASE : str = current_node SCREAMING_SNAKE_CASE : Optional[int] = current_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node for _ in range(1 , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Tuple = Node() SCREAMING_SNAKE_CASE : Dict = current_node SCREAMING_SNAKE_CASE : Optional[Any] = previous_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node SCREAMING_SNAKE_CASE : Union[str, Any] = self.front SCREAMING_SNAKE_CASE : List[str] = previous_node def _A ( self : Union[str, Any] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _A ( self : Optional[int] ): self.check_can_perform_operation() return self.front.data if self.front else None def _A ( self : Optional[int] , UpperCAmelCase_ : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE : List[str] = self.rear.next if self.rear: SCREAMING_SNAKE_CASE : Dict = data def _A ( self : List[str] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE : List[str] = self.front.data SCREAMING_SNAKE_CASE : Optional[int] = None return data SCREAMING_SNAKE_CASE : List[str] = self.front SCREAMING_SNAKE_CASE : List[str] = old_front.next SCREAMING_SNAKE_CASE : Optional[int] = old_front.data SCREAMING_SNAKE_CASE : List[str] = None return data def _A ( self : Any ): if self.is_empty(): raise Exception("Empty Queue" ) def _A ( self : Optional[Any] ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any | None = None SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """JukeboxPriorConfig""", """JukeboxVQVAEConfig""", ], """tokenization_jukebox""": ["""JukeboxTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """JukeboxModel""", """JukeboxPreTrainedModel""", """JukeboxVQVAE""", """JukeboxPrior""", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) snake_case = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ ( lowercase , lowercase , lowercase = 1 , lowercase = 1 , lowercase = 1.0E4 , lowercase = False , lowercase = 1.0 , ): """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even''' SCREAMING_SNAKE_CASE : Union[str, Any] = float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE : Optional[Any] = min_timescale * jnp.exp(jnp.arange(lowercase , dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE : Optional[int] = jnp.expand_dims(lowercase , 1 ) * jnp.expand_dims(lowercase , 0 ) # scale embeddings SCREAMING_SNAKE_CASE : Optional[int] = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate([jnp.cos(lowercase ), jnp.sin(lowercase )] , axis=1 ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.concatenate([jnp.sin(lowercase ), jnp.cos(lowercase )] , axis=1 ) SCREAMING_SNAKE_CASE : Tuple = jnp.reshape(lowercase , [jnp.shape(lowercase )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.silu(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(UpperCAmelCase_ ) return temb class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : bool = False UpperCamelCase_ : float = 1 @nn.compact def __call__( self : Optional[int] , UpperCAmelCase_ : int ): return get_sinusoidal_embeddings( UpperCAmelCase_ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
62
1
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : str = 1 @register_to_config def __init__( self : int , UpperCAmelCase_ : int = 1000 , UpperCAmelCase_ : Optional[Union[np.ndarray, List[float]]] = None ): # set `betas`, `alphas`, `timesteps` self.set_timesteps(UpperCAmelCase_ ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : Tuple = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : List[Any] = 4 # running values SCREAMING_SNAKE_CASE : Optional[Any] = [] def _A ( self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, torch.device] = None ): SCREAMING_SNAKE_CASE : Optional[int] = num_inference_steps SCREAMING_SNAKE_CASE : Dict = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : List[Any] = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : List[Any] = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : str = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : Union[str, Any] = timesteps.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = [] def _A ( self : List[str] , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : int , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : bool = True , ): if self.num_inference_steps is None: raise ValueError( "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" ) SCREAMING_SNAKE_CASE : List[str] = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : str = timestep_index + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCAmelCase_ ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : List[str] = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : List[Any] = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : Union[str, Any] = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : List[str] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : Dict = self._get_prev_sample(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCAmelCase_ ) def _A ( self : str , UpperCAmelCase_ : torch.FloatTensor , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ): return sample def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Tuple = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : str = self.betas[timestep_index] SCREAMING_SNAKE_CASE : List[str] = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : Union[str, Any] = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : Union[str, Any] = (sample - sigma * ets) / max(UpperCAmelCase_ , 1E-8 ) SCREAMING_SNAKE_CASE : Dict = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : List[Any] ): return self.config.num_train_timesteps
62
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ : Any = '''image_segmenter''' UpperCamelCase_ : int = CLIPSegForImageSegmentation UpperCamelCase_ : Optional[Any] = ['''image''', '''text'''] UpperCamelCase_ : int = ['''image'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): with torch.no_grad(): SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits return logits def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
62
1
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : int = 6 ): SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None self.create_linked_list(UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Optional[int] = Node() SCREAMING_SNAKE_CASE : str = current_node SCREAMING_SNAKE_CASE : Optional[int] = current_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node for _ in range(1 , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Tuple = Node() SCREAMING_SNAKE_CASE : Dict = current_node SCREAMING_SNAKE_CASE : Optional[Any] = previous_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node SCREAMING_SNAKE_CASE : Union[str, Any] = self.front SCREAMING_SNAKE_CASE : List[str] = previous_node def _A ( self : Union[str, Any] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _A ( self : Optional[int] ): self.check_can_perform_operation() return self.front.data if self.front else None def _A ( self : Optional[int] , UpperCAmelCase_ : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE : List[str] = self.rear.next if self.rear: SCREAMING_SNAKE_CASE : Dict = data def _A ( self : List[str] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE : List[str] = self.front.data SCREAMING_SNAKE_CASE : Optional[int] = None return data SCREAMING_SNAKE_CASE : List[str] = self.front SCREAMING_SNAKE_CASE : List[str] = old_front.next SCREAMING_SNAKE_CASE : Optional[int] = old_front.data SCREAMING_SNAKE_CASE : List[str] = None return data def _A ( self : Any ): if self.is_empty(): raise Exception("Empty Queue" ) def _A ( self : Optional[Any] ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any | None = None SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
62
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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BlenderbotSmallTokenizer UpperCamelCase_ : int = False def _A ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] SCREAMING_SNAKE_CASE : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : List[Any] , **UpperCAmelCase_ : str ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : int = "adapt act apte" return input_text, output_text def _A ( self : str ): SCREAMING_SNAKE_CASE : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : List[str] = ["adapt", "act", "ap@@", "te"] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1384] SCREAMING_SNAKE_CASE : str = "I am a small frog." SCREAMING_SNAKE_CASE : List[Any] = tok([src_text] , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : int = tok.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) SCREAMING_SNAKE_CASE : Tuple = "I am a small frog ." SCREAMING_SNAKE_CASE : Optional[int] = "." SCREAMING_SNAKE_CASE : Dict = tok(UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : Optional[Any] = tok(UpperCAmelCase_ )["input_ids"] assert encoded[-1] == encoded_dot[0]
62
1
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / "cache" SCREAMING_SNAKE_CASE : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE : List[Any] = JsonDatasetReader(lowercase , cache_dir=lowercase , keep_in_memory=lowercase ).read() _check_json_dataset(lowercase , lowercase ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = tmp_path / "cache" SCREAMING_SNAKE_CASE : List[Any] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : List[Any] = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE : List[Any] = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE : Optional[Any] = JsonDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read() _check_json_dataset(lowercase , lowercase ) @pytest.mark.parametrize( "features" , [ None, {"col_3": "float64", "col_1": "string", "col_2": "int64"}, ] , ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = tmp_path / "cache" SCREAMING_SNAKE_CASE : int = {"col_3": "float64", "col_1": "string", "col_2": "int64"} SCREAMING_SNAKE_CASE : Tuple = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE : Union[str, Any] = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE : Any = JsonDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read() assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = {"col_2": "int64", "col_3": "float64", "col_1": "string"} SCREAMING_SNAKE_CASE : Optional[Any] = features.copy() SCREAMING_SNAKE_CASE : str = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE : int = tmp_path / "cache" SCREAMING_SNAKE_CASE : Optional[int] = JsonDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read() assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = tmp_path / "cache" SCREAMING_SNAKE_CASE : Dict = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : List[Any] = JsonDatasetReader(lowercase , cache_dir=lowercase , split=lowercase ).read() _check_json_dataset(lowercase , lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" if issubclass(lowercase , lowercase ): SCREAMING_SNAKE_CASE : List[str] = jsonl_path elif issubclass(lowercase , lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = [jsonl_path] SCREAMING_SNAKE_CASE : str = tmp_path / "cache" SCREAMING_SNAKE_CASE : Dict = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : int = JsonDatasetReader(lowercase , cache_dir=lowercase ).read() _check_json_dataset(lowercase , lowercase ) def lowerCamelCase__ ( lowercase , lowercase , lowercase=("train",) ): """simple docstring""" assert isinstance(lowercase , lowercase ) for split in splits: SCREAMING_SNAKE_CASE : Optional[Any] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / "cache" SCREAMING_SNAKE_CASE : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE : List[str] = JsonDatasetReader({"train": jsonl_path} , cache_dir=lowercase , keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase , lowercase ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = tmp_path / "cache" SCREAMING_SNAKE_CASE : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : Union[str, Any] = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE : List[str] = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE : Any = JsonDatasetReader({"train": jsonl_path} , features=lowercase , cache_dir=lowercase ).read() _check_json_datasetdict(lowercase , lowercase ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" if split: SCREAMING_SNAKE_CASE : Dict = {split: jsonl_path} else: SCREAMING_SNAKE_CASE : str = "train" SCREAMING_SNAKE_CASE : Dict = {"train": jsonl_path, "test": jsonl_path} SCREAMING_SNAKE_CASE : Tuple = tmp_path / "cache" SCREAMING_SNAKE_CASE : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : int = JsonDatasetReader(lowercase , cache_dir=lowercase ).read() _check_json_datasetdict(lowercase , lowercase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return json.load(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE : '''simple docstring''' @pytest.mark.parametrize("lines, load_json_function" , [(True, load_json_lines), (False, load_json)] ) def _A ( self : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Any ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCAmelCase_ , UpperCAmelCase_ , lines=UpperCAmelCase_ ).write() buffer.seek(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = load_json_function(UpperCAmelCase_ ) assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert isinstance(exported_content[0] , UpperCAmelCase_ ) assert len(UpperCAmelCase_ ) == 10 @pytest.mark.parametrize( "orient, container, keys, len_at" , [ ("records", list, {"tokens", "labels", "answers", "id"}, None), ("split", dict, {"columns", "data"}, "data"), ("index", dict, set("0123456789" ), None), ("columns", dict, {"tokens", "labels", "answers", "id"}, "tokens"), ("values", list, None, None), ("table", dict, {"schema", "data"}, "data"), ] , ) def _A ( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCAmelCase_ , UpperCAmelCase_ , lines=UpperCAmelCase_ , orient=UpperCAmelCase_ ).write() buffer.seek(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = load_json(UpperCAmelCase_ ) assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCAmelCase_ , "keys" ) and not hasattr(exported_content[0] , "keys" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCAmelCase_ ) == 10 @pytest.mark.parametrize("lines, load_json_function" , [(True, load_json_lines), (False, load_json)] ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCAmelCase_ , UpperCAmelCase_ , lines=UpperCAmelCase_ , num_proc=2 ).write() buffer.seek(0 ) SCREAMING_SNAKE_CASE : int = load_json_function(UpperCAmelCase_ ) assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert isinstance(exported_content[0] , UpperCAmelCase_ ) assert len(UpperCAmelCase_ ) == 10 @pytest.mark.parametrize( "orient, container, keys, len_at" , [ ("records", list, {"tokens", "labels", "answers", "id"}, None), ("split", dict, {"columns", "data"}, "data"), ("index", dict, set("0123456789" ), None), ("columns", dict, {"tokens", "labels", "answers", "id"}, "tokens"), ("values", list, None, None), ("table", dict, {"schema", "data"}, "data"), ] , ) def _A ( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCAmelCase_ , UpperCAmelCase_ , lines=UpperCAmelCase_ , orient=UpperCAmelCase_ , num_proc=2 ).write() buffer.seek(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = load_json(UpperCAmelCase_ ) assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCAmelCase_ , "keys" ) and not hasattr(exported_content[0] , "keys" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCAmelCase_ ) == 10 def _A ( self : int , UpperCAmelCase_ : Dict ): with pytest.raises(UpperCAmelCase_ ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCAmelCase_ , UpperCAmelCase_ , num_proc=0 ) @pytest.mark.parametrize("compression, extension" , [("gzip", "gz"), ("bz2", "bz2"), ("xz", "xz")] ) def _A ( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : str = tmp_path_factory.mktemp("data" ) / f'''test.json.{extension}''' SCREAMING_SNAKE_CASE : Union[str, Any] = str(shared_datadir / f'''test_file.json.{extension}''' ) JsonDatasetWriter(UpperCAmelCase_ , UpperCAmelCase_ , compression=UpperCAmelCase_ ).write() with fsspec.open(UpperCAmelCase_ , "rb" , compression="infer" ) as f: SCREAMING_SNAKE_CASE : Union[str, Any] = f.read() with fsspec.open(UpperCAmelCase_ , "rb" , compression="infer" ) as f: SCREAMING_SNAKE_CASE : str = f.read() assert exported_content == original_content
62
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] snake_case = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = torch.load(lowercase , map_location="cpu" ) return sd def lowerCamelCase__ ( lowercase , lowercase , lowercase=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE : Union[str, Any] = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE : Any = new_key.replace(name_pair[0] , name_pair[1] ) SCREAMING_SNAKE_CASE : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE : Union[str, Any] = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = "pretraining" if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Any = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 512} SCREAMING_SNAKE_CASE : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = {"visual_embedding_dim": 2048} SCREAMING_SNAKE_CASE : str = "vqa_advanced" elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Tuple = {"visual_embedding_dim": 2048, "num_labels": 3129} SCREAMING_SNAKE_CASE : Optional[Any] = "vqa" elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = { "visual_embedding_dim": 1024, "num_labels": 2, } SCREAMING_SNAKE_CASE : Tuple = "nlvr" SCREAMING_SNAKE_CASE : List[Any] = VisualBertConfig(**lowercase ) # Load State Dict SCREAMING_SNAKE_CASE : List[str] = load_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Any = get_new_dict(lowercase , lowercase ) if model_type == "pretraining": SCREAMING_SNAKE_CASE : int = VisualBertForPreTraining(lowercase ) elif model_type == "vqa": SCREAMING_SNAKE_CASE : Tuple = VisualBertForQuestionAnswering(lowercase ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE : List[Any] = VisualBertForVisualReasoning(lowercase ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE : Optional[Any] = VisualBertForMultipleChoice(lowercase ) model.load_state_dict(lowercase ) # Save Checkpoints Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
62
1
import qiskit def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = qiskit.Aer.get_backend("aer_simulator" ) SCREAMING_SNAKE_CASE : Dict = qiskit.QuantumCircuit(4 , 2 ) # encode inputs in qubits 0 and 1 if bita == 1: qc_ha.x(0 ) if bita == 1: qc_ha.x(1 ) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0 , 2 ) qc_ha.cx(1 , 2 ) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0 , 1 , 3 ) qc_ha.barrier() # extract outputs qc_ha.measure(2 , 0 ) # extract XOR value qc_ha.measure(3 , 1 ) # extract AND value # Execute the circuit on the qasm simulator SCREAMING_SNAKE_CASE : List[Any] = qiskit.execute(lowercase , lowercase , shots=1000 ) # Return the histogram data of the results of the experiment return job.result().get_counts(lowercase ) if __name__ == "__main__": snake_case = half_adder(1, 1) print(F"""Half Adder Output Qubit Counts: {counts}""")
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """JukeboxPriorConfig""", """JukeboxVQVAEConfig""", ], """tokenization_jukebox""": ["""JukeboxTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """JukeboxModel""", """JukeboxPreTrainedModel""", """JukeboxVQVAE""", """JukeboxPrior""", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : str = ['''image_processor''', '''tokenizer'''] UpperCamelCase_ : Tuple = '''BlipImageProcessor''' UpperCamelCase_ : List[str] = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : int = False super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.image_processor def __call__( self : Optional[int] , UpperCAmelCase_ : ImageInput = None , UpperCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_ : Union[bool, str, TruncationStrategy] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase_ : str , ): if images is None and text is None: raise ValueError("You have to specify either images or text." ) # Get only text if images is None: SCREAMING_SNAKE_CASE : str = self.tokenizer SCREAMING_SNAKE_CASE : int = 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_ , ) return text_encoding # add pixel_values SCREAMING_SNAKE_CASE : Tuple = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) if text is not None: SCREAMING_SNAKE_CASE : Tuple = 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_ , ) else: SCREAMING_SNAKE_CASE : Tuple = None if text_encoding is not None: encoding_image_processor.update(UpperCAmelCase_ ) return encoding_image_processor def _A ( self : Optional[int] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Union[str, Any] ): return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[int] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[Any] ): return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) @property def _A ( self : Dict ): SCREAMING_SNAKE_CASE : List[str] = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
62
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ snake_case = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ snake_case = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _A ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def _A ( self : List[Any] , UpperCAmelCase_ : List[List[List[str]]] , UpperCAmelCase_ : List[List[str]] , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCAmelCase_ , hypotheses=UpperCAmelCase_ , min_len=UpperCAmelCase_ , max_len=UpperCAmelCase_ ) }
62
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : List[Any]=18 , UpperCAmelCase_ : Tuple=30 , UpperCAmelCase_ : List[Any]=400 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Dict=True , ): SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Optional[Any] = parent SCREAMING_SNAKE_CASE : List[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : List[str] = image_size SCREAMING_SNAKE_CASE : str = min_resolution SCREAMING_SNAKE_CASE : Optional[int] = max_resolution SCREAMING_SNAKE_CASE : Union[str, Any] = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Tuple = apply_ocr def _A ( self : Union[str, Any] ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Dict = LayoutLMvaImageProcessingTester(self ) @property def _A ( self : List[str] ): return self.image_processor_tester.prepare_image_processor_dict() def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_resize" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "size" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "apply_ocr" ) ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def _A ( self : List[str] ): pass def _A ( self : Optional[Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : Any = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase_ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase_ ) # Test batched SCREAMING_SNAKE_CASE : Any = image_processing(UpperCAmelCase_ , 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.size["height"], self.image_processor_tester.size["width"], ) , ) def _A ( self : Optional[int] ): # Initialize image_processing SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[Any] = image_processing(UpperCAmelCase_ , 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.size["height"], self.image_processor_tester.size["width"], ) , ) def _A ( self : List[Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = 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.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[Any] = image_processing(UpperCAmelCase_ , 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.size["height"], self.image_processor_tester.size["width"], ) , ) def _A ( self : Union[str, Any] ): # with apply_OCR = True SCREAMING_SNAKE_CASE : Any = LayoutLMvaImageProcessor() from datasets import load_dataset SCREAMING_SNAKE_CASE : Dict = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) SCREAMING_SNAKE_CASE : Any = Image.open(ds[0]["file"] ).convert("RGB" ) SCREAMING_SNAKE_CASE : Dict = image_processing(UpperCAmelCase_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 SCREAMING_SNAKE_CASE : Tuple = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 SCREAMING_SNAKE_CASE : int = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase_ ) self.assertListEqual(encoding.boxes , UpperCAmelCase_ ) # with apply_OCR = False SCREAMING_SNAKE_CASE : Tuple = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = image_processing(UpperCAmelCase_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = row, column SCREAMING_SNAKE_CASE : Optional[Any] = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE : Optional[Any] = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = f'''%{max_element_length}s''' # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE : Optional[int] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Dict ): return str(self ) def _A ( self : Optional[int] , UpperCAmelCase_ : tuple[int, int] ): if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase_ : tuple[int, int] ): assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : int , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ): assert self.validate_indicies(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : Any = self[r, c] + another[r, c] return result def __neg__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ): return self + (-another) def __mul__( self : Dict , UpperCAmelCase_ : int | float | Matrix ): if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE : Any = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE : List[str] = f'''Unsupported type given for another ({type(UpperCAmelCase_ )})''' raise TypeError(UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : List[str] = self[r, c] return result def _A ( self : Union[str, Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE : Tuple = v.transpose() SCREAMING_SNAKE_CASE : int = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE : str = 1 print(F'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE : Optional[int] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 2, -3 SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase , lowercase )}''' ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() testa()
62
1
from __future__ import annotations class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : int = data SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None def lowerCamelCase__ ( lowercase ): # In Order traversal of the tree """simple docstring""" if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowerCamelCase__ ( lowercase ): """simple docstring""" if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCamelCase__ ( ): # Main function for testing. """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = Node(1 ) SCREAMING_SNAKE_CASE : Dict = Node(2 ) SCREAMING_SNAKE_CASE : List[Any] = Node(3 ) SCREAMING_SNAKE_CASE : List[Any] = Node(4 ) SCREAMING_SNAKE_CASE : Tuple = Node(5 ) SCREAMING_SNAKE_CASE : str = Node(6 ) SCREAMING_SNAKE_CASE : List[Any] = Node(7 ) SCREAMING_SNAKE_CASE : str = Node(8 ) SCREAMING_SNAKE_CASE : Any = Node(9 ) print(is_full_binary_tree(lowercase ) ) print(depth_of_tree(lowercase ) ) print("Tree is: " ) display(lowercase ) if __name__ == "__main__": main()
62
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } snake_case = { """junnyu/roformer_chinese_small""": 1_536, """junnyu/roformer_chinese_base""": 1_536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } snake_case = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = RoFormerTokenizer def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : List[str]="[UNK]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : Any="[PAD]" , UpperCAmelCase_ : List[str]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : List[str] , ): 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_ , ) SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase_ ) != strip_accents ): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : List[str] = strip_accents SCREAMING_SNAKE_CASE : Tuple = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : Tuple , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = d SCREAMING_SNAKE_CASE : Dict = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE : Any = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase_ ) ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _A ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : List[Any] = [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 _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Optional[int] = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
62
1
import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = BigBirdConfig.from_json_file(lowercase ) print(F'''Building PyTorch model from configuration: {config}''' ) if is_trivia_qa: SCREAMING_SNAKE_CASE : Any = BigBirdForQuestionAnswering(lowercase ) else: SCREAMING_SNAKE_CASE : Optional[int] = BigBirdForPreTraining(lowercase ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(lowercase , lowercase , is_trivia_qa=lowercase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = 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.""" ) snake_case = 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 )
62
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE : Optional[int] = str(abs(lowercase ) ) SCREAMING_SNAKE_CASE : str = [list(lowercase ) for char in range(len(lowercase ) )] for index in range(len(lowercase ) ): num_transpositions[index].pop(lowercase ) return max( int("".join(list(lowercase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
62
1
import flax.linen as nn import jax import jax.numpy as jnp class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int UpperCamelCase_ : jnp.dtype = jnp.floataa def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[Any] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Optional[int] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = hidden_states.shape SCREAMING_SNAKE_CASE : int = jax.image.resize( UpperCAmelCase_ , shape=(batch, height * 2, width * 2, channels) , method="nearest" , ) SCREAMING_SNAKE_CASE : Optional[int] = self.conv(UpperCAmelCase_ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int UpperCamelCase_ : jnp.dtype = jnp.floataa def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Dict , UpperCAmelCase_ : Tuple ): # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) SCREAMING_SNAKE_CASE : int = self.conv(UpperCAmelCase_ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int UpperCamelCase_ : int = None UpperCamelCase_ : float = 0.0 UpperCamelCase_ : bool = None UpperCamelCase_ : jnp.dtype = jnp.floataa def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = self.in_channels if self.out_channels is None else self.out_channels SCREAMING_SNAKE_CASE : Tuple = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) SCREAMING_SNAKE_CASE : Optional[int] = nn.Conv( UpperCAmelCase_ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) SCREAMING_SNAKE_CASE : Dict = nn.Dense(UpperCAmelCase_ , dtype=self.dtype ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Dropout(self.dropout_prob ) SCREAMING_SNAKE_CASE : Tuple = nn.Conv( UpperCAmelCase_ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) SCREAMING_SNAKE_CASE : Any = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut SCREAMING_SNAKE_CASE : Optional[int] = None if use_nin_shortcut: SCREAMING_SNAKE_CASE : str = nn.Conv( UpperCAmelCase_ , kernel_size=(1, 1) , strides=(1, 1) , padding="VALID" , dtype=self.dtype , ) def __call__( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str=True ): SCREAMING_SNAKE_CASE : Any = hidden_states SCREAMING_SNAKE_CASE : Tuple = self.norma(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = nn.swish(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.conva(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.time_emb_proj(nn.swish(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : Tuple = jnp.expand_dims(jnp.expand_dims(UpperCAmelCase_ , 1 ) , 1 ) SCREAMING_SNAKE_CASE : List[str] = hidden_states + temb SCREAMING_SNAKE_CASE : Dict = self.norma(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = nn.swish(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.dropout(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.conva(UpperCAmelCase_ ) if self.conv_shortcut is not None: SCREAMING_SNAKE_CASE : Tuple = self.conv_shortcut(UpperCAmelCase_ ) return hidden_states + residual
62
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = 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 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : int ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) 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 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _A ( self : Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9E-2
62
1
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } snake_case = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" for attribute in key.split("." ): SCREAMING_SNAKE_CASE : str = getattr(lowercase , lowercase ) if weight_type is not None: SCREAMING_SNAKE_CASE : List[str] = getattr(lowercase , lowercase ).shape else: SCREAMING_SNAKE_CASE : str = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": SCREAMING_SNAKE_CASE : Union[str, Any] = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE : Any = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE : List[str] = value elif weight_type == "bias": SCREAMING_SNAKE_CASE : int = value else: SCREAMING_SNAKE_CASE : Optional[int] = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : str = fairseq_model.state_dict() SCREAMING_SNAKE_CASE : str = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight SCREAMING_SNAKE_CASE : List[str] = None for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE : List[Any] = False if "conv_layers" in name: load_conv_layer( lowercase , lowercase , lowercase , lowercase , hf_model.config.feat_extract_norm == "group" , ) SCREAMING_SNAKE_CASE : Optional[int] = True elif name.split("." )[0] == "proj": SCREAMING_SNAKE_CASE : Optional[Any] = fairseq_model.proj SCREAMING_SNAKE_CASE : str = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: SCREAMING_SNAKE_CASE : Dict = True if "*" in mapped_key: SCREAMING_SNAKE_CASE : Dict = name.split(lowercase )[0].split("." )[-2] SCREAMING_SNAKE_CASE : Optional[Any] = mapped_key.replace("*" , lowercase ) if "weight_g" in name: SCREAMING_SNAKE_CASE : List[str] = "weight_g" elif "weight_v" in name: SCREAMING_SNAKE_CASE : Optional[Any] = "weight_v" elif "bias" in name: SCREAMING_SNAKE_CASE : Tuple = "bias" elif "weight" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = "weight" else: SCREAMING_SNAKE_CASE : Dict = None set_recursively(lowercase , lowercase , lowercase , lowercase , lowercase ) continue if not is_used: unused_weights.append(lowercase ) logger.warning(F'''Unused weights: {unused_weights}''' ) return proj_weight def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = full_name.split("conv_layers." )[-1] SCREAMING_SNAKE_CASE : Tuple = name.split("." ) SCREAMING_SNAKE_CASE : int = int(items[0] ) SCREAMING_SNAKE_CASE : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) SCREAMING_SNAKE_CASE : Tuple = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE : List[str] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) SCREAMING_SNAKE_CASE : int = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) SCREAMING_SNAKE_CASE : Optional[int] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = emb.weight.shape SCREAMING_SNAKE_CASE : Optional[int] = nn.Linear(lowercase , lowercase , bias=lowercase ) SCREAMING_SNAKE_CASE : str = emb.weight.data return lin_layer def lowerCamelCase__ ( lowercase ): """simple docstring""" with open(lowercase , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE : List[Any] = f.readlines() SCREAMING_SNAKE_CASE : Union[str, Any] = [line.split(" " )[0] for line in lines] SCREAMING_SNAKE_CASE : Optional[int] = len(lowercase ) SCREAMING_SNAKE_CASE : List[Any] = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update(dict(zip(lowercase , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = WavaVecaConfig.from_pretrained(lowercase ) SCREAMING_SNAKE_CASE : Dict = SpeechaTextaConfig.from_pretrained( lowercase , vocab_size=lowercase , decoder_layers=lowercase , do_stable_layer_norm=lowercase ) SCREAMING_SNAKE_CASE : str = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowercase , return_attention_mask=lowercase , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) SCREAMING_SNAKE_CASE : Dict = model[0].eval() # set weights for wav2vec2 encoder SCREAMING_SNAKE_CASE : str = WavaVecaModel(lowercase ) SCREAMING_SNAKE_CASE : List[str] = recursively_load_weights_wavaveca(model.encoder , lowercase ) SCREAMING_SNAKE_CASE : Tuple = SpeechaTextaForCausalLM(lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=lowercase ) # set output linear layer unexpected_keys.remove("embed_out" ) SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F'''The following keys are missing when loading the decoder weights: {missing_keys}''' ) logger.warning(F'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}''' ) SCREAMING_SNAKE_CASE : Dict = SpeechEncoderDecoderModel(encoder=lowercase , decoder=lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = False # add projection layer SCREAMING_SNAKE_CASE : Any = nn.Parameter(projection_layer.weight ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(projection_layer.bias ) SCREAMING_SNAKE_CASE : Dict = create_vocab_dict(lowercase ) with open(os.path.join(lowercase , "vocab.json" ) , "w" ) as fp: json.dump(lowercase , lowercase ) SCREAMING_SNAKE_CASE : Tuple = SpeechaTextaTokenizer(os.path.join(lowercase , "vocab.json" ) ) tokenizer.save_pretrained(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = hf_wavavec.config.to_dict() SCREAMING_SNAKE_CASE : Tuple = tokenizer.pad_token_id SCREAMING_SNAKE_CASE : Any = tokenizer.bos_token_id SCREAMING_SNAKE_CASE : str = tokenizer.eos_token_id SCREAMING_SNAKE_CASE : int = "speech_to_text_2" SCREAMING_SNAKE_CASE : List[str] = "wav2vec2" SCREAMING_SNAKE_CASE : Dict = SpeechEncoderDecoderConfig.from_dict(lowercase ) hf_wavavec.save_pretrained(lowercase ) feature_extractor.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument( """--encoder_config_path""", default="""facebook/wav2vec2-large-lv60""", type=str, help="""Path to hf encoder wav2vec2 checkpoint config""", ) parser.add_argument( """--decoder_config_path""", default="""facebook/s2t-small-mustc-en-fr-st""", type=str, help="""Path to hf decoder s2t checkpoint config""", ) parser.add_argument("""--vocab_size""", default=10_224, type=int, help="""Vocab size of decoder""") parser.add_argument("""--num_decoder_layers""", default=7, type=int, help="""Number of decoder layers""") snake_case = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
62
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 ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE : List[Any] = [144, 192, 240] SCREAMING_SNAKE_CASE : Tuple = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [96, 120, 144] SCREAMING_SNAKE_CASE : Dict = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [64, 80, 96] SCREAMING_SNAKE_CASE : List[str] = [16, 16, 24, 48, 64, 80, 320] SCREAMING_SNAKE_CASE : int = 0.05 SCREAMING_SNAKE_CASE : int = 2.0 if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : str = 512 SCREAMING_SNAKE_CASE : List[str] = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 21 SCREAMING_SNAKE_CASE : Dict = "pascal-voc-id2label.json" else: SCREAMING_SNAKE_CASE : Optional[Any] = 1000 SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : Any = "huggingface/label-files" SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowercase , lowercase , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE : List[str] = {int(lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} return config def lowerCamelCase__ ( lowercase , lowercase=False ): """simple docstring""" for i in range(1 , 6 ): if F'''layer_{i}.''' in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(F'''layer_{i}.''' , F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: SCREAMING_SNAKE_CASE : Dict = name.replace("conv_1." , "conv_stem." ) if ".block." in name: SCREAMING_SNAKE_CASE : List[str] = name.replace(".block." , "." ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE : str = name.replace("exp_1x1" , "expand_1x1" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("red_1x1" , "reduce_1x1" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".local_rep.conv_3x3." , ".conv_kxk." ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE : int = name.replace(".local_rep.conv_1x1." , ".conv_1x1." ) if ".norm." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".norm." , ".normalization." ) if ".conv." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".conv." , ".convolution." ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".conv_proj." , ".conv_projection." ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.layer.{j}.''' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.''' ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("expand_1x1" , "downsampling_layer.expand_1x1" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE : str = name.replace("conv_3x3" , "downsampling_layer.conv_3x3" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("reduce_1x1" , "downsampling_layer.reduce_1x1" ) for i in range(2 , 5 ): if F'''.global_rep.{i}.weight''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.global_rep.{i}.weight''' , ".layernorm.weight" ) if F'''.global_rep.{i}.bias''' in name: SCREAMING_SNAKE_CASE : str = name.replace(F'''.global_rep.{i}.bias''' , ".layernorm.bias" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".global_rep." , ".transformer." ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_mha.0." , ".layernorm_before." ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_mha.1.out_proj." , ".attention.output.dense." ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(".pre_norm_ffn.0." , ".layernorm_after." ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_ffn.1." , ".intermediate.dense." ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_ffn.4." , ".output.dense." ) if ".transformer." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".transformer." , ".transformer.layer." ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE : int = name.replace(".aspp_layer." , "." ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".aspp_pool." , "." ) if "seg_head." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("seg_head." , "segmentation_head." ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("segmentation_head.classifier.classifier." , "segmentation_head.classifier." ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("classifier.fc." , "classifier." ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE : List[Any] = "mobilevit." + name return name def lowerCamelCase__ ( lowercase , lowercase , lowercase=False ): """simple docstring""" if base_model: SCREAMING_SNAKE_CASE : Optional[int] = "" else: SCREAMING_SNAKE_CASE : Any = "mobilevit." for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = orig_state_dict.pop(lowercase ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE : int = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.split("." ) SCREAMING_SNAKE_CASE : Any = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE : List[Any] = int(key_split[3] ) SCREAMING_SNAKE_CASE : List[Any] = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) SCREAMING_SNAKE_CASE : int = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE : Union[str, Any] = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: SCREAMING_SNAKE_CASE : str = val[:dim] SCREAMING_SNAKE_CASE : Union[str, Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] else: SCREAMING_SNAKE_CASE : List[Any] = val return orig_state_dict def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_mobilevit_config(lowercase ) # load original state_dict SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(lowercase , map_location="cpu" ) # load 🤗 model if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : List[str] = MobileViTForSemanticSegmentation(lowercase ).eval() else: SCREAMING_SNAKE_CASE : str = MobileViTForImageClassification(lowercase ).eval() SCREAMING_SNAKE_CASE : Any = convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE : List[Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE : List[Any] = model(**lowercase ) SCREAMING_SNAKE_CASE : str = outputs.logits if mobilevit_name.startswith("deeplabv3_" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] , lowercase , atol=1E-4 ) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE : Dict = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] , lowercase , atol=1E-4 ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if push_to_hub: SCREAMING_SNAKE_CASE : List[str] = { "mobilevit_s": "mobilevit-small", "mobilevit_xs": "mobilevit-x-small", "mobilevit_xxs": "mobilevit-xx-small", "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small", "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small", "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small", } print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE : int = model_mapping[mobilevit_name] image_processor.push_to_hub(lowercase , organization="apple" ) model.push_to_hub(lowercase , organization="apple" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, 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 = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
62
1
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_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 torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=13 , UpperCAmelCase_ : List[Any]=32 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Optional[Any]=3 , UpperCAmelCase_ : int=16 , UpperCAmelCase_ : Any=[1, 2, 1] , UpperCAmelCase_ : Any=[2, 2, 4] , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Union[str, Any]=2.0 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : int=0.0 , UpperCAmelCase_ : str=0.0 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[Any]="gelu" , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Optional[Any]=0.02 , UpperCAmelCase_ : int=1E-5 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : Optional[Any]=8 , UpperCAmelCase_ : Dict=["stage1", "stage2", "stage3"] , UpperCAmelCase_ : Optional[int]=[1, 2, 3] , ): SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Optional[int] = batch_size SCREAMING_SNAKE_CASE : List[str] = image_size SCREAMING_SNAKE_CASE : Optional[Any] = patch_size SCREAMING_SNAKE_CASE : List[str] = num_channels SCREAMING_SNAKE_CASE : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE : Tuple = depths SCREAMING_SNAKE_CASE : List[str] = num_heads SCREAMING_SNAKE_CASE : Any = window_size SCREAMING_SNAKE_CASE : List[Any] = mlp_ratio SCREAMING_SNAKE_CASE : Optional[int] = qkv_bias SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[str] = drop_path_rate SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : int = use_absolute_embeddings SCREAMING_SNAKE_CASE : Optional[int] = patch_norm SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = is_training SCREAMING_SNAKE_CASE : str = scope SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : Optional[int] = type_sequence_label_size SCREAMING_SNAKE_CASE : Optional[Any] = encoder_stride SCREAMING_SNAKE_CASE : int = out_features SCREAMING_SNAKE_CASE : int = out_indices def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_config() return config, pixel_values, labels def _A ( self : List[str] ): return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _A ( self : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : Dict = MaskFormerSwinModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE : Optional[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _A ( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : int = MaskFormerSwinBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : str = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = ["stem"] SCREAMING_SNAKE_CASE : List[str] = MaskFormerSwinBackbone(config=UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) UpperCamelCase_ : Tuple = {'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {} UpperCamelCase_ : Any = False UpperCamelCase_ : Tuple = False UpperCamelCase_ : int = False UpperCamelCase_ : int = False UpperCamelCase_ : int = False def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = MaskFormerSwinModelTester(self ) SCREAMING_SNAKE_CASE : Tuple = ConfigTester(self , config_class=UpperCAmelCase_ , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def _A ( self : Optional[Any] ): pass def _A ( self : Union[str, Any] ): 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 : Union[str, Any] ): return def _A ( self : Dict ): SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*UpperCAmelCase_ ) @unittest.skip("Swin does not use inputs_embeds" ) def _A ( self : Tuple ): pass @unittest.skip("Swin does not support feedforward chunking" ) def _A ( self : Any ): pass def _A ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : List[str] = model_class(UpperCAmelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase_ , nn.Linear ) ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Dict = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def _A ( self : Optional[Any] ): pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def _A ( self : List[str] ): pass def _A ( self : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Optional[Any] = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE : List[Any] = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) # Swin has a different seq_length SCREAMING_SNAKE_CASE : Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Dict = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Optional[int] = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : Optional[Any] = 3 SCREAMING_SNAKE_CASE : Dict = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE : List[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE : Dict = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[Any] = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Any = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def _A ( self : List[Any] ): pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def _A ( self : int ): pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def _A ( self : Optional[int] ): pass def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : Optional[Any] = 0 return t def check_equivalence(UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any]={} ): with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(**UpperCAmelCase_ , return_dict=UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ , return_dict=UpperCAmelCase_ , **UpperCAmelCase_ ).to_tuple() def recursive_check(UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple ): if isinstance(UpperCAmelCase_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase_ , UpperCAmelCase_ ): recursive_check(UpperCAmelCase_ , UpperCAmelCase_ ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(UpperCAmelCase_ , UpperCAmelCase_ ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(UpperCAmelCase_ ) , set_nan_tensor_to_zero(UpperCAmelCase_ ) , atol=1E-5 ) , msg=( "Tuple and dict output are not equal. Difference:" f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(UpperCAmelCase_ ).any()} and `inf`: {torch.isinf(UpperCAmelCase_ )}. Dict has''' f''' `nan`: {torch.isnan(UpperCAmelCase_ ).any()} and `inf`: {torch.isinf(UpperCAmelCase_ )}.''' ) , ) recursive_check(UpperCAmelCase_ , UpperCAmelCase_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Tuple = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , {"output_hidden_states": True} ) SCREAMING_SNAKE_CASE : int = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , {"output_hidden_states": True} ) @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase , lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = (MaskFormerSwinBackbone,) if is_torch_available() else () UpperCamelCase_ : Optional[int] = MaskFormerSwinConfig def _A ( self : str ): SCREAMING_SNAKE_CASE : str = MaskFormerSwinModelTester(self ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : int = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: SCREAMING_SNAKE_CASE : List[Any] = backbone_class(UpperCAmelCase_ ) backbone.to(UpperCAmelCase_ ) backbone.eval() SCREAMING_SNAKE_CASE : Union[str, Any] = backbone(**UpperCAmelCase_ ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , UpperCAmelCase_ ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True SCREAMING_SNAKE_CASE : Optional[int] = backbone(**UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: SCREAMING_SNAKE_CASE : Any = backbone(**UpperCAmelCase_ , output_attentions=UpperCAmelCase_ ) self.assertIsNotNone(outputs.attentions )
62
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case = datasets.load_iris() snake_case = np.array(data["""data"""]) snake_case = np.array(data["""target"""]) snake_case = data["""target_names"""] snake_case , snake_case , snake_case , snake_case = train_test_split(X, y) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase=5 ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = zip(lowercase , lowercase ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE : Optional[int] = [] for data_point in data: SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE : List[Any] = [i[1] for i in sorted(lowercase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE : List[Any] = Counter(lowercase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
62
1
import argparse import copy def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {} with open(lowercase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE : List[str] = [] _list.append([line.split()[1], line.split()[2]] ) SCREAMING_SNAKE_CASE : Optional[int] = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: SCREAMING_SNAKE_CASE : List[str] = [] _list.append([line.split()[0], line.split()[2]] ) SCREAMING_SNAKE_CASE : List[Any] = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" with open(lowercase ) as f: SCREAMING_SNAKE_CASE : str = f.read(1 ) SCREAMING_SNAKE_CASE : List[Any] = start_node SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : Optional[Any] = start_node SCREAMING_SNAKE_CASE : Optional[Any] = 0 while visiting not in first_solution: SCREAMING_SNAKE_CASE : Dict = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(lowercase ) and k[0] not in first_solution: SCREAMING_SNAKE_CASE : Union[str, Any] = k[1] SCREAMING_SNAKE_CASE : List[str] = k[0] first_solution.append(lowercase ) SCREAMING_SNAKE_CASE : int = distance_of_first_solution + int(lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = best_node first_solution.append(lowercase ) SCREAMING_SNAKE_CASE : List[Any] = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 SCREAMING_SNAKE_CASE : Any = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [] for n in solution[1:-1]: SCREAMING_SNAKE_CASE : Optional[Any] = solution.index(lowercase ) for kn in solution[1:-1]: SCREAMING_SNAKE_CASE : Optional[Any] = solution.index(lowercase ) if n == kn: continue SCREAMING_SNAKE_CASE : Optional[Any] = copy.deepcopy(lowercase ) SCREAMING_SNAKE_CASE : Tuple = kn SCREAMING_SNAKE_CASE : List[Any] = n SCREAMING_SNAKE_CASE : str = 0 for k in _tmp[:-1]: SCREAMING_SNAKE_CASE : List[Any] = _tmp[_tmp.index(lowercase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: SCREAMING_SNAKE_CASE : Tuple = distance + int(i[1] ) _tmp.append(lowercase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) SCREAMING_SNAKE_CASE : Optional[int] = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda lowercase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : Dict = first_solution SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[int] = distance_of_first_solution SCREAMING_SNAKE_CASE : int = solution while count <= iters: SCREAMING_SNAKE_CASE : Optional[Any] = find_neighborhood(lowercase , lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : List[Any] = neighborhood[index_of_best_solution] SCREAMING_SNAKE_CASE : Optional[Any] = len(lowercase ) - 1 SCREAMING_SNAKE_CASE : Dict = False while not found: SCREAMING_SNAKE_CASE : Dict = 0 while i < len(lowercase ): if best_solution[i] != solution[i]: SCREAMING_SNAKE_CASE : int = best_solution[i] SCREAMING_SNAKE_CASE : str = solution[i] break SCREAMING_SNAKE_CASE : Tuple = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) SCREAMING_SNAKE_CASE : Any = True SCREAMING_SNAKE_CASE : Dict = best_solution[:-1] SCREAMING_SNAKE_CASE : int = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: SCREAMING_SNAKE_CASE : Any = cost SCREAMING_SNAKE_CASE : int = solution else: SCREAMING_SNAKE_CASE : int = index_of_best_solution + 1 SCREAMING_SNAKE_CASE : Tuple = neighborhood[index_of_best_solution] if len(lowercase ) >= size: tabu_list.pop(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = count + 1 return best_solution_ever, best_cost def lowerCamelCase__ ( lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : str = generate_neighbours(args.File ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = generate_first_solution( args.File , lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = tabu_search( lowercase , lowercase , lowercase , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": snake_case = argparse.ArgumentParser(description="""Tabu Search""") parser.add_argument( """-f""", """--File""", type=str, help="""Path to the file containing the data""", required=True, ) parser.add_argument( """-i""", """--Iterations""", type=int, help="""How many iterations the algorithm should perform""", required=True, ) parser.add_argument( """-s""", """--Size""", type=int, help="""Size of the tabu list""", required=True ) # Pass the arguments to main method main(parser.parse_args())
62
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''xlm-prophetnet''' UpperCamelCase_ : Tuple = ['''past_key_values'''] UpperCamelCase_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Dict , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[Union[str, Callable]] = "gelu" , UpperCAmelCase_ : Optional[int] = 3_0522 , UpperCAmelCase_ : Optional[int] = 1024 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[int] = 512 , UpperCAmelCase_ : Optional[float] = 0.02 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 2 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 128 , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[float] = 0.0 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 2 , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = num_encoder_layers SCREAMING_SNAKE_CASE : Any = num_encoder_attention_heads SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers SCREAMING_SNAKE_CASE : List[Any] = num_decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE : Dict = ngram SCREAMING_SNAKE_CASE : Any = num_buckets SCREAMING_SNAKE_CASE : str = relative_max_distance SCREAMING_SNAKE_CASE : str = disable_ngram_loss SCREAMING_SNAKE_CASE : Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : int = use_cache super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , add_cross_attention=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def _A ( self : int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
62
1
from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def lowerCamelCase__ ( lowercase , lowercase , lowercase = "x" , lowercase = 10**-10 , lowercase = 1 , ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = symbols(lowercase ) SCREAMING_SNAKE_CASE : Tuple = lambdify(lowercase , lowercase ) SCREAMING_SNAKE_CASE : str = lambdify(lowercase , diff(lowercase , lowercase ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = starting_point while True: if diff_function(lowercase ) != 0: SCREAMING_SNAKE_CASE : str = prev_guess - multiplicity * func(lowercase ) / diff_function( lowercase ) else: raise ZeroDivisionError("Could not find root" ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess SCREAMING_SNAKE_CASE : str = next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""") # Find root of polynomial # Find fourth Root of 5 print(F"""The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5j)}""") # Find value of e print( """The root of log(y) - 1 = 0 is """, F"""{newton_raphson('log(y) - 1', 2, variable='y')}""", ) # Exponential Roots print( """The root of exp(x) - 1 = 0 is""", F"""{newton_raphson('exp(x) - 1', 10, precision=0.005)}""", ) # Find root of cos(x) print(F"""The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}""")
62
import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, 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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = KandinskyVaaPipeline UpperCamelCase_ : List[Any] = [ '''image_embeds''', '''negative_image_embeds''', ] UpperCamelCase_ : Tuple = ['''image_embeds''', '''negative_image_embeds'''] UpperCamelCase_ : Any = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCamelCase_ : List[str] = False @property def _A ( self : List[Any] ): return 32 @property def _A ( self : List[Any] ): return 32 @property def _A ( self : Any ): return self.time_input_dim @property def _A ( self : Union[str, Any] ): return self.time_input_dim * 4 @property def _A ( self : Tuple ): return 100 @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } SCREAMING_SNAKE_CASE : str = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def _A ( self : int ): 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 : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = self.dummy_unet SCREAMING_SNAKE_CASE : str = self.dummy_movq SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="epsilon" , thresholding=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _A ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]=0 ): SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = "cpu" SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : Tuple = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array( [0.6_237_976, 1.0, 0.36_441_332, 1.0, 0.70_639_634, 0.29_877_186, 0.85_652_125, 0.5_216_843, 0.54_454_046] ) 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy" ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Tuple = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = "red cat, 4k photo" SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="np" , ) SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
62
1
import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE : int = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE : str = torch.optim.lr_scheduler.OneCycleLR(lowercase , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE : Optional[Any] = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE : Optional[Any] = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def lowerCamelCase__ ( lowercase ): """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(lowercase ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' @require_cuda def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[Any] = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = Accelerator(cpu=UpperCAmelCase_ ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = Accelerator() SCREAMING_SNAKE_CASE : int = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE : int = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE : Tuple = False assert state.sync_gradients is False GradientState._reset_state() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = Accelerator() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = create_components() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = accelerator.prepare(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[Any] = Accelerator() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = create_components() accelerator.prepare(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def _A ( self : Any ): PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*UpperCAmelCase_ : str , **UpperCAmelCase_ : Union[str, Any] ): pass with patch("torch.cuda.set_device" , UpperCAmelCase_ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE : Tuple = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def _A ( self : int ): SCREAMING_SNAKE_CASE : Tuple = Accelerator() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = create_components() accelerator.prepare(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = get_signature(UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(UpperCAmelCase_ ) # make sure random weights don't match load_random_weights(UpperCAmelCase_ ) self.assertTrue(abs(model_signature - get_signature(UpperCAmelCase_ ) ) > 1E-3 ) # make sure loaded weights match accelerator.load_state(UpperCAmelCase_ ) self.assertTrue(abs(model_signature - get_signature(UpperCAmelCase_ ) ) < 1E-3 ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = create_components() accelerator.prepare(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = get_signature(UpperCAmelCase_ ) # saving hook def save_config(UpperCAmelCase_ : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : str = {"class_name": models[0].__class__.__name__} with open(os.path.join(UpperCAmelCase_ , "data.json" ) , "w" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) # loading hook def load_config(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] ): with open(os.path.join(UpperCAmelCase_ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE : Optional[int] = json.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = config["class_name"] SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.register_save_state_pre_hook(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = accelerator.register_load_state_pre_hook(UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(UpperCAmelCase_ ) # make sure random weights don't match with hooks load_random_weights(UpperCAmelCase_ ) self.assertTrue(abs(model_signature - get_signature(UpperCAmelCase_ ) ) > 1E-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE : Optional[int] = "random" # make sure loaded weights match with hooks accelerator.load_state(UpperCAmelCase_ ) self.assertTrue(abs(model_signature - get_signature(UpperCAmelCase_ ) ) < 1E-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(UpperCAmelCase_ ) # make sure random weights don't match with hooks removed load_random_weights(UpperCAmelCase_ ) self.assertTrue(abs(model_signature - get_signature(UpperCAmelCase_ ) ) > 1E-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(UpperCAmelCase_ ) self.assertTrue(abs(model_signature - get_signature(UpperCAmelCase_ ) ) < 1E-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def _A ( self : str ): SCREAMING_SNAKE_CASE : Tuple = Accelerator() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = create_components() SCREAMING_SNAKE_CASE : int = None # This should work SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = accelerator.prepare( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertTrue(dummy_obj is None ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Accelerator() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = create_components() SCREAMING_SNAKE_CASE : Optional[int] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = accelerator.prepare( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual( getattr(UpperCAmelCase_ , "_is_accelerate_prepared" , UpperCAmelCase_ ) , UpperCAmelCase_ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(UpperCAmelCase_ , "_is_accelerate_prepared" , UpperCAmelCase_ ) , UpperCAmelCase_ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(UpperCAmelCase_ , "_is_accelerate_prepared" , UpperCAmelCase_ ) , UpperCAmelCase_ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(UpperCAmelCase_ , "_is_accelerate_prepared" , UpperCAmelCase_ ) , UpperCAmelCase_ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(UpperCAmelCase_ , "_is_accelerate_prepared" , UpperCAmelCase_ ) , UpperCAmelCase_ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(UpperCAmelCase_ , "_is_accelerate_prepared" , UpperCAmelCase_ ) , UpperCAmelCase_ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def _A ( self : Dict ): from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE : int = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=UpperCAmelCase_ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE : str = Accelerator() # This should work SCREAMING_SNAKE_CASE : List[str] = accelerator.prepare(UpperCAmelCase_ ) @slow @require_bnb def _A ( self : Tuple ): from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE : Tuple = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE : List[str] = infer_auto_device_map(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = "cpu" SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=UpperCAmelCase_ , load_in_abit=UpperCAmelCase_ , llm_inta_enable_fpaa_cpu_offload=UpperCAmelCase_ ) # This should not work and get value error with self.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = accelerator.prepare(UpperCAmelCase_ ) @slow @require_bnb @require_multi_gpu def _A ( self : int ): from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE : Union[str, Any] = infer_auto_device_map(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : List[str] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=UpperCAmelCase_ , device_map=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = Accelerator() # This should not work and get value error with self.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = accelerator.prepare(UpperCAmelCase_ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def _A ( self : Dict ): from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE : int = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE : Union[str, Any] = infer_auto_device_map(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 1 SCREAMING_SNAKE_CASE : List[Any] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=UpperCAmelCase_ , device_map=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : str = Accelerator() # This should work SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.prepare(UpperCAmelCase_ ) @require_cuda def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[Any] = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE : str = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE : str = Accelerator(cpu=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = accelerator.prepare(UpperCAmelCase_ )
62
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput snake_case = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : int , *UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Tuple=None , **UpperCAmelCase_ : Optional[Any] ): super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = eval_examples SCREAMING_SNAKE_CASE : List[Any] = post_process_function SCREAMING_SNAKE_CASE : Any = quant_trainer_args SCREAMING_SNAKE_CASE : Optional[Any] = 128 # default number of calibration samples def _A ( self : Optional[Any] , UpperCAmelCase_ : Tuple=None ): if calib_dataset is None and self.calib_dataset is None: raise ValueError("Trainer: calibration requires an calib_dataset." ) SCREAMING_SNAKE_CASE : str = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE : str = self._remove_unused_columns(UpperCAmelCase_ , description="Calibration" ) return DataLoader( UpperCAmelCase_ , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=UpperCAmelCase_ , ) def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[int]=None ): SCREAMING_SNAKE_CASE : Any = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_calib_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args , calib=UpperCAmelCase_ ) model.eval() quant_trainer.enable_calibration(UpperCAmelCase_ ) logger.info("***** Running calibration *****" ) logger.info(f''' Num examples = {self.calib_num}''' ) logger.info(f''' Batch size = {calib_dataloader.batch_size}''' ) for step, inputs in enumerate(UpperCAmelCase_ ): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.prediction_step(UpperCAmelCase_ , UpperCAmelCase_ , prediction_loss_only=UpperCAmelCase_ ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : Optional[int] = model def _A ( self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str = "eval" ): SCREAMING_SNAKE_CASE : List[str] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : Tuple = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : int = eval_loop( UpperCAmelCase_ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : int = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE : List[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions ) SCREAMING_SNAKE_CASE : Any = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = metrics.pop(UpperCAmelCase_ ) self.log(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : List[Any] = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : List[str] = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCAmelCase_ ) return metrics def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : str = "test" ): SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(UpperCAmelCase_ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Tuple = self.compute_metrics SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : str = eval_loop( UpperCAmelCase_ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : Union[str, Any] = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Optional[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions , "predict" ) SCREAMING_SNAKE_CASE : str = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : str = metrics.pop(UpperCAmelCase_ ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCAmelCase_ ) def _A ( self : Any , UpperCAmelCase_ : int="./" ): SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = next(iter(UpperCAmelCase_ ) ) # saving device - to make it consistent SCREAMING_SNAKE_CASE : int = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) # convert to tuple SCREAMING_SNAKE_CASE : Tuple = tuple(v.to(UpperCAmelCase_ ) for k, v in batch.items() ) logger.info("Converting model to be onnx compatible" ) from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Any = self.model.to(UpperCAmelCase_ ) model.eval() model.float() SCREAMING_SNAKE_CASE : str = model.module if hasattr(UpperCAmelCase_ , "module" ) else model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : List[Any] = os.path.join(UpperCAmelCase_ , "model.onnx" ) logger.info(f'''exporting model to {output_model_file}''' ) SCREAMING_SNAKE_CASE : int = {0: "batch_size", 1: "seq_len"} torch.onnx.export( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , export_params=UpperCAmelCase_ , opset_version=13 , do_constant_folding=UpperCAmelCase_ , input_names=["input_ids", "attention_mask", "token_type_ids"] , output_names=["output_start_logits", "output_end_logits"] , dynamic_axes={ "input_ids": axes, "attention_mask": axes, "token_type_ids": axes, "output_start_logits": axes, "output_end_logits": axes, } , verbose=UpperCAmelCase_ , ) logger.info("onnx export finished" )
62
1
import math import tensorflow as tf from packaging import version def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = tf.convert_to_tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = tf.convert_to_tensor(lowercase ) SCREAMING_SNAKE_CASE : str = tf.cast(math.pi , x.dtype ) SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(0.044715 , x.dtype ) SCREAMING_SNAKE_CASE : List[Any] = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(lowercase , 3 )) )) return x * cdf def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = tf.convert_to_tensor(lowercase ) return x * tf.tanh(tf.math.softplus(lowercase ) ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = tf.convert_to_tensor(lowercase ) SCREAMING_SNAKE_CASE : Tuple = tf.cast(0.044715 , x.dtype ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.cast(0.7978845608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = tf.convert_to_tensor(lowercase ) SCREAMING_SNAKE_CASE : List[str] = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return tf.clip_by_value(_gelu(lowercase ) , -10 , 10 ) def lowerCamelCase__ ( lowercase , lowercase=-1 ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = tf.split(lowercase , 2 , axis=lowercase ) return a * tf.math.sigmoid(lowercase ) if version.parse(tf.version.VERSION) >= version.parse("""2.4"""): def lowerCamelCase__ ( lowercase ): """simple docstring""" return tf.keras.activations.gelu(lowercase , approximate=lowercase ) snake_case = tf.keras.activations.gelu snake_case = approximate_gelu_wrap else: snake_case = _gelu snake_case = _gelu_new snake_case = { """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 lowerCamelCase__ ( lowercase ): """simple docstring""" if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(F'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )
62
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = LayoutLMTokenizer UpperCamelCase_ : str = LayoutLMTokenizerFast UpperCamelCase_ : Any = True UpperCamelCase_ : Optional[Any] = True def _A ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : str , **UpperCAmelCase_ : Optional[int] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Any = "UNwant\u00E9d,running" SCREAMING_SNAKE_CASE : Union[str, Any] = "unwanted, running" return input_text, output_text def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [7, 4, 5, 10, 8, 9] ) def _A ( self : List[str] ): pass
62
1
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not all(char in "01" for char in bin_string ): raise ValueError("Non-binary value was passed to the function" ) if not bin_string: raise ValueError("Empty string was passed to the function" ) SCREAMING_SNAKE_CASE : Any = "" while len(lowercase ) % 3 != 0: SCREAMING_SNAKE_CASE : Optional[int] = "0" + bin_string SCREAMING_SNAKE_CASE : Union[str, Any] = [ bin_string[index : index + 3] for index in range(len(lowercase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: SCREAMING_SNAKE_CASE : Tuple = 0 for index, val in enumerate(lowercase ): oct_val += int(2 ** (2 - index) * int(lowercase ) ) oct_string += str(lowercase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
62
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = os.path.join(args.tf_model_dir , "parameters.json" ) SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(open(lowercase ).read() ) if not params: raise ValueError( F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.''' ) if not args.output.endswith(".pt" ): SCREAMING_SNAKE_CASE : Optional[int] = args.output + ".pt" SCREAMING_SNAKE_CASE : Any = OrderedDict() with tf.device("/CPU:0" ): SCREAMING_SNAKE_CASE : Union[str, Any] = tf.train.load_checkpoint(args.tf_model_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): SCREAMING_SNAKE_CASE : Any = reader.get_tensor(lowercase ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9] ) elif key_name.startswith("pasts/out" ): SCREAMING_SNAKE_CASE : Optional[int] = 8 SCREAMING_SNAKE_CASE : List[Any] = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time SCREAMING_SNAKE_CASE : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.startswith("model/moe" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/softmlp/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): SCREAMING_SNAKE_CASE : Optional[int] = key_name[-9:-7] for i in range(16 ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) SCREAMING_SNAKE_CASE : List[str] = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name.startswith("model/mlp" ): SCREAMING_SNAKE_CASE : str = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.mlp.wi.weight" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/p1/bias" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.wi.bias" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/kernel" ): SCREAMING_SNAKE_CASE : str = "model.blocks.%d.feed_forward.mlp.wo.weight" % player SCREAMING_SNAKE_CASE : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/bias" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.feed_forward.mlp.wo.bias" % player SCREAMING_SNAKE_CASE : str = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) elif key_name.startswith("model/ln" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.norm.bias" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : List[str] = "model.blocks.%d.feed_forward.norm.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/att" ): SCREAMING_SNAKE_CASE : Optional[int] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum SCREAMING_SNAKE_CASE : List[str] = state[:, 0, :, :] SCREAMING_SNAKE_CASE : Tuple = state[:, 1, :, :] SCREAMING_SNAKE_CASE : List[Any] = state[:, 2, :, :] SCREAMING_SNAKE_CASE : Tuple = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : int = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/o/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif key_name.startswith("model/an" ): SCREAMING_SNAKE_CASE : int = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.self_attn.norm.bias" % player SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.self_attn.norm.weight" % player SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): SCREAMING_SNAKE_CASE : str = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] SCREAMING_SNAKE_CASE : List[str] = "model.%s.weight" % nlayer SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) if key_name.startswith("model/wte" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "lm_head.weight" SCREAMING_SNAKE_CASE : List[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/wob" ): SCREAMING_SNAKE_CASE : List[Any] = "final_logits_bias" SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : List[str] = state.reshape((1, -1) ) SCREAMING_SNAKE_CASE : int = torch.tensor(lowercase ) elif key_name == "model/dense/kernel": SCREAMING_SNAKE_CASE : Optional[int] = "model.last_project.weight" SCREAMING_SNAKE_CASE : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name == "model/dense_1/bias": SCREAMING_SNAKE_CASE : str = "model.last_project.bias" SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) torch.save(lowercase , args.output ) if __name__ == "__main__": snake_case = argparse.ArgumentParser( description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""") parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""") snake_case = parser.parse_args() convert_tf_gptsan_to_pt(args)
62
1
from ...processing_utils import ProcessorMixin class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = ['''image_processor''', '''feature_extractor'''] UpperCamelCase_ : Any = '''TvltImageProcessor''' UpperCamelCase_ : Tuple = '''TvltFeatureExtractor''' def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any ): super().__init__(image_processor=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = image_processor SCREAMING_SNAKE_CASE : Union[str, Any] = feature_extractor def __call__( self : Tuple , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=False , UpperCAmelCase_ : str=False , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[Any] , ): if images is None and audio is None: raise ValueError("You need to specify either an `images` or `audio` input to process." ) SCREAMING_SNAKE_CASE : str = None if images is not None: SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor(UpperCAmelCase_ , mask_pixel=UpperCAmelCase_ , *UpperCAmelCase_ , **UpperCAmelCase_ ) if images_mixed is not None: SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor(UpperCAmelCase_ , is_mixed=UpperCAmelCase_ , *UpperCAmelCase_ , **UpperCAmelCase_ ) if audio is not None: SCREAMING_SNAKE_CASE : Optional[int] = self.feature_extractor( UpperCAmelCase_ , *UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , mask_audio=UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = {} if audio is not None: output_dict.update(UpperCAmelCase_ ) if images is not None: output_dict.update(UpperCAmelCase_ ) if images_mixed_dict is not None: output_dict.update(UpperCAmelCase_ ) return output_dict @property def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[Any] = self.image_processor.model_input_names SCREAMING_SNAKE_CASE : Any = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
62
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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: on SCREAMING_SNAKE_CASE : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Optional[int] = { "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], } SCREAMING_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 _A ( self : List[Any] , **UpperCAmelCase_ : List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Union[str, Any] , **UpperCAmelCase_ : Any ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Union[str, Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE : Any = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) SCREAMING_SNAKE_CASE : str = 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 _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : int = image_processor(UpperCAmelCase_ , return_tensors="np" ) SCREAMING_SNAKE_CASE : Optional[int] = 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 _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = "lower newer" SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : int = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = "lower newer" SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Optional[Any] = processor.batch_decode(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = "lower newer" SCREAMING_SNAKE_CASE : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
62
1
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : str = ['''flax'''] def __init__( self : Any , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[Any] ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[Any] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Optional[int] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Tuple ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : str = ['''flax'''] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[int] ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : str , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : List[Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[int] ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''flax'''] def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : str ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : Optional[int] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : int ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[Any] ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Dict = ['''flax'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[Any] ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : Tuple , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[str] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Dict , *UpperCAmelCase_ : str , **UpperCAmelCase_ : int ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ['''flax'''] def __init__( self : int , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : int , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Optional[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Optional[int] ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = ['''flax'''] def __init__( self : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : int ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : str , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : int ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : str , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[Any] ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : int = ['''flax'''] def __init__( self : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Tuple ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : Any , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : List[str] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Optional[Any] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = ['''flax'''] def __init__( self : Dict , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Tuple ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : List[Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Tuple ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Any , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[int] ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = ['''flax'''] def __init__( self : Optional[int] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Tuple ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : int , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Optional[Any] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : str ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''flax'''] def __init__( self : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : List[str] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[str] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Optional[Any] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = ['''flax'''] def __init__( self : List[str] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[str] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : List[str] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Any ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : int = ['''flax'''] def __init__( self : List[Any] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[Any] ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : Dict , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[Any] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : Dict , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Dict ): requires_backends(cls , ["flax"] ) class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = ['''flax'''] def __init__( self : Optional[int] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : str ): requires_backends(self , ["flax"] ) @classmethod def _A ( cls : Optional[Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[str] ): requires_backends(cls , ["flax"] ) @classmethod def _A ( cls : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : str ): requires_backends(cls , ["flax"] )
62
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "tf_padding" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "depth_multiplier" ) ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]=13 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : int=0.25 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : Dict=8 , UpperCAmelCase_ : Optional[int]=6 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : str="relu6" , UpperCAmelCase_ : List[str]=1280 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : int = depth_multiplier SCREAMING_SNAKE_CASE : str = depth_divisible_by SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth SCREAMING_SNAKE_CASE : int = expand_ratio SCREAMING_SNAKE_CASE : Tuple = tf_padding SCREAMING_SNAKE_CASE : List[str] = output_stride SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion SCREAMING_SNAKE_CASE : Any = finegrained_output SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = scope def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels, pixel_labels def _A ( self : Optional[int] ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Dict = MobileNetVaForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase_ : List[Any] = ( { '''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification, '''image-segmentation''': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Any = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : int = False UpperCamelCase_ : str = False def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def _A ( self : List[Any] ): pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def _A ( self : Dict ): pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def _A ( self : Union[str, Any] ): pass def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): def check_hidden_states_output(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 16 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : str = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def _A ( self : Optional[Any] ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : int = MobileNetVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Optional[int] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ ) # verify the logits SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : int = model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.tensor( [ [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]], [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]], [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
62
1
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = '''efficientformer''' def __init__( self : str , UpperCAmelCase_ : List[int] = [3, 2, 6, 4] , UpperCAmelCase_ : List[int] = [48, 96, 224, 448] , UpperCAmelCase_ : List[bool] = [True, True, True, True] , UpperCAmelCase_ : int = 448 , UpperCAmelCase_ : int = 32 , UpperCAmelCase_ : int = 4 , UpperCAmelCase_ : int = 7 , UpperCAmelCase_ : int = 5 , UpperCAmelCase_ : int = 8 , UpperCAmelCase_ : int = 4 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 16 , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : float = 1E-5 , UpperCAmelCase_ : str = "gelu" , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : float = 1E-12 , UpperCAmelCase_ : int = 224 , UpperCAmelCase_ : float = 1E-05 , **UpperCAmelCase_ : str , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = hidden_act SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : int = hidden_sizes SCREAMING_SNAKE_CASE : Dict = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = patch_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE : Any = depths SCREAMING_SNAKE_CASE : List[str] = mlp_expansion_ratio SCREAMING_SNAKE_CASE : Tuple = downsamples SCREAMING_SNAKE_CASE : Tuple = dim SCREAMING_SNAKE_CASE : Tuple = key_dim SCREAMING_SNAKE_CASE : List[Any] = attention_ratio SCREAMING_SNAKE_CASE : Optional[Any] = resolution SCREAMING_SNAKE_CASE : Dict = pool_size SCREAMING_SNAKE_CASE : Any = downsample_patch_size SCREAMING_SNAKE_CASE : Dict = downsample_stride SCREAMING_SNAKE_CASE : Optional[int] = downsample_pad SCREAMING_SNAKE_CASE : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE : List[str] = num_metaad_blocks SCREAMING_SNAKE_CASE : List[str] = distillation SCREAMING_SNAKE_CASE : Any = use_layer_scale SCREAMING_SNAKE_CASE : Dict = layer_scale_init_value SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : int = batch_norm_eps
62
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" def constraint_to_multiple_of(lowercase , lowercase , lowercase=0 , lowercase=None ): SCREAMING_SNAKE_CASE : Any = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : int = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Tuple = (output_size, output_size) if isinstance(lowercase , lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_image_size(lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Tuple = output_height / input_height SCREAMING_SNAKE_CASE : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width SCREAMING_SNAKE_CASE : List[str] = scale_width else: # fit height SCREAMING_SNAKE_CASE : Optional[Any] = scale_height SCREAMING_SNAKE_CASE : int = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase ) SCREAMING_SNAKE_CASE : Dict = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase ) return (new_height, new_width) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase_ : str , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = size if size is not None else {"height": 384, "width": 384} SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : int = ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample SCREAMING_SNAKE_CASE : List[str] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self : Tuple , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : int , ): SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = get_resize_output_image_size( UpperCAmelCase_ , output_size=(size["height"], size["width"]) , keep_aspect_ratio=UpperCAmelCase_ , multiple=UpperCAmelCase_ , ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Dict , ): return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ): return normalize(UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : Optional[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : List[str] = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Any = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Tuple = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Tuple = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Tuple] = None ): SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : str = [] for idx in range(len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
62
1
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCamelCase__ ( lowercase , lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : str = None if token is not None: SCREAMING_SNAKE_CASE : Any = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} SCREAMING_SNAKE_CASE : str = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' SCREAMING_SNAKE_CASE : Optional[int] = requests.get(lowercase , headers=lowercase ).json() SCREAMING_SNAKE_CASE : List[str] = {} try: job_links.update({job["name"]: job["html_url"] for job in result["jobs"]} ) SCREAMING_SNAKE_CASE : List[str] = math.ceil((result["total_count"] - 100) / 100 ) for i in range(lowercase ): SCREAMING_SNAKE_CASE : Dict = requests.get(url + F'''&page={i + 2}''' , headers=lowercase ).json() job_links.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return job_links except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCamelCase__ ( lowercase , lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = None if token is not None: SCREAMING_SNAKE_CASE : str = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} SCREAMING_SNAKE_CASE : Optional[int] = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' SCREAMING_SNAKE_CASE : str = requests.get(lowercase , headers=lowercase ).json() SCREAMING_SNAKE_CASE : Optional[Any] = {} try: artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]} ) SCREAMING_SNAKE_CASE : Dict = math.ceil((result["total_count"] - 100) / 100 ) for i in range(lowercase ): SCREAMING_SNAKE_CASE : Dict = requests.get(url + F'''&page={i + 2}''' , headers=lowercase ).json() artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]} ) return artifacts except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = None if token is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} SCREAMING_SNAKE_CASE : Optional[int] = requests.get(lowercase , headers=lowercase , allow_redirects=lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = result.headers["Location"] SCREAMING_SNAKE_CASE : List[str] = requests.get(lowercase , allow_redirects=lowercase ) SCREAMING_SNAKE_CASE : List[str] = os.path.join(lowercase , F'''{artifact_name}.zip''' ) with open(lowercase , "wb" ) as fp: fp.write(response.content ) def lowerCamelCase__ ( lowercase , lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Any = None with zipfile.ZipFile(lowercase ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(lowercase ) as f: for line in f: SCREAMING_SNAKE_CASE : List[str] = line.decode("UTF-8" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs SCREAMING_SNAKE_CASE : Optional[Any] = line[: line.index(": " )] SCREAMING_SNAKE_CASE : Any = line[line.index(": " ) + len(": " ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("FAILED " ): # `test` is the test method that failed SCREAMING_SNAKE_CASE : int = line[len("FAILED " ) :] failed_tests.append(lowercase ) elif filename == "job_name.txt": SCREAMING_SNAKE_CASE : Optional[Any] = line if len(lowercase ) != len(lowercase ): raise ValueError( F'''`errors` and `failed_tests` should have the same number of elements. Got {len(lowercase )} for `errors` ''' F'''and {len(lowercase )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' " problem." ) SCREAMING_SNAKE_CASE : Union[str, Any] = None if job_name and job_links: SCREAMING_SNAKE_CASE : Tuple = job_links.get(lowercase , lowercase ) # A list with elements of the form (line of error, error, failed test) SCREAMING_SNAKE_CASE : List[Any] = [x + [y] + [job_link] for x, y in zip(lowercase , lowercase )] return result def lowerCamelCase__ ( lowercase , lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Optional[int] = [os.path.join(lowercase , lowercase ) for p in os.listdir(lowercase ) if p.endswith(".zip" )] for p in paths: errors.extend(get_errors_from_single_artifact(lowercase , job_links=lowercase ) ) return errors def lowerCamelCase__ ( lowercase , lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : str = Counter() counter.update([x[1] for x in logs] ) SCREAMING_SNAKE_CASE : str = counter.most_common() SCREAMING_SNAKE_CASE : str = {} for error, count in counts: if error_filter is None or error not in error_filter: SCREAMING_SNAKE_CASE : List[str] = {"count": count, "failed_tests": [(x[2], x[0]) for x in logs if x[1] == error]} SCREAMING_SNAKE_CASE : Union[str, Any] = dict(sorted(r.items() , key=lambda lowercase : item[1]["count"] , reverse=lowercase ) ) return r def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = test.split("::" )[0] if test.startswith("tests/models/" ): SCREAMING_SNAKE_CASE : Dict = test.split("/" )[2] else: SCREAMING_SNAKE_CASE : Optional[int] = None return test def lowerCamelCase__ ( lowercase , lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [(x[0], x[1], get_model(x[2] )) for x in logs] SCREAMING_SNAKE_CASE : Dict = [x for x in logs if x[2] is not None] SCREAMING_SNAKE_CASE : Optional[Any] = {x[2] for x in logs} SCREAMING_SNAKE_CASE : List[Any] = {} for test in tests: SCREAMING_SNAKE_CASE : str = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) SCREAMING_SNAKE_CASE : Tuple = counter.most_common() SCREAMING_SNAKE_CASE : Optional[Any] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} SCREAMING_SNAKE_CASE : Dict = sum(error_counts.values() ) if n_errors > 0: SCREAMING_SNAKE_CASE : Dict = {"count": n_errors, "errors": error_counts} SCREAMING_SNAKE_CASE : List[Any] = dict(sorted(r.items() , key=lambda lowercase : item[1]["count"] , reverse=lowercase ) ) return r def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = "| no. | error | status |" SCREAMING_SNAKE_CASE : Tuple = "|-:|:-|:-|" SCREAMING_SNAKE_CASE : int = [header, sep] for error in reduced_by_error: SCREAMING_SNAKE_CASE : Optional[int] = reduced_by_error[error]["count"] SCREAMING_SNAKE_CASE : str = F'''| {count} | {error[:100]} | |''' lines.append(lowercase ) return "\n".join(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = "| model | no. of errors | major error | count |" SCREAMING_SNAKE_CASE : Any = "|-:|-:|-:|-:|" SCREAMING_SNAKE_CASE : int = [header, sep] for model in reduced_by_model: SCREAMING_SNAKE_CASE : Optional[int] = reduced_by_model[model]["count"] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = list(reduced_by_model[model]["errors"].items() )[0] SCREAMING_SNAKE_CASE : List[str] = F'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(lowercase ) return "\n".join(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") snake_case = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) snake_case = get_job_links(args.workflow_run_id, token=args.token) snake_case = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: snake_case = k.find(""" / """) snake_case = k[index + len(""" / """) :] snake_case = v with open(os.path.join(args.output_dir, """job_links.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) snake_case = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) snake_case = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error snake_case = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors snake_case = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, """errors.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) snake_case = reduce_by_error(errors) snake_case = reduce_by_model(errors) snake_case = make_github_table(reduced_by_error) snake_case = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, """reduced_by_error.txt"""), """w""", encoding="""UTF-8""") as fp: fp.write(sa) with open(os.path.join(args.output_dir, """reduced_by_model.txt"""), """w""", encoding="""UTF-8""") as fp: fp.write(sa)
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : int = 6 ): SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None self.create_linked_list(UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Optional[int] = Node() SCREAMING_SNAKE_CASE : str = current_node SCREAMING_SNAKE_CASE : Optional[int] = current_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node for _ in range(1 , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Tuple = Node() SCREAMING_SNAKE_CASE : Dict = current_node SCREAMING_SNAKE_CASE : Optional[Any] = previous_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node SCREAMING_SNAKE_CASE : Union[str, Any] = self.front SCREAMING_SNAKE_CASE : List[str] = previous_node def _A ( self : Union[str, Any] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _A ( self : Optional[int] ): self.check_can_perform_operation() return self.front.data if self.front else None def _A ( self : Optional[int] , UpperCAmelCase_ : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE : List[str] = self.rear.next if self.rear: SCREAMING_SNAKE_CASE : Dict = data def _A ( self : List[str] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE : List[str] = self.front.data SCREAMING_SNAKE_CASE : Optional[int] = None return data SCREAMING_SNAKE_CASE : List[str] = self.front SCREAMING_SNAKE_CASE : List[str] = old_front.next SCREAMING_SNAKE_CASE : Optional[int] = old_front.data SCREAMING_SNAKE_CASE : List[str] = None return data def _A ( self : Any ): if self.is_empty(): raise Exception("Empty Queue" ) def _A ( self : Optional[Any] ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any | None = None SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
62
1
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: snake_case = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : str=18 , UpperCAmelCase_ : str=30 , UpperCAmelCase_ : Optional[int]=400 , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Any=None , ): SCREAMING_SNAKE_CASE : Any = size if size is not None else {"height": 20, "width": 20} SCREAMING_SNAKE_CASE : Optional[int] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : List[str] = image_size SCREAMING_SNAKE_CASE : Optional[int] = min_resolution SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Optional[Any] = do_normalize SCREAMING_SNAKE_CASE : Any = do_convert_rgb SCREAMING_SNAKE_CASE : Any = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE : Union[str, Any] = patch_size if patch_size is not None else {"height": 16, "width": 16} def _A ( self : List[str] ): return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" SCREAMING_SNAKE_CASE : Tuple = Image.open(requests.get(UpperCAmelCase_ , stream=UpperCAmelCase_ ).raw ).convert("RGB" ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = PixaStructImageProcessor if is_vision_available() else None def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = PixaStructImageProcessingTester(self ) @property def _A ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_normalize" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_convert_rgb" ) ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE : Optional[Any] = 2048 SCREAMING_SNAKE_CASE : Tuple = image_processor(UpperCAmelCase_ , return_tensors="pt" , max_patches=UpperCAmelCase_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0_606 ) , atol=1E-3 , rtol=1E-3 ) ) def _A ( self : str ): # Initialize image_processor SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[int] = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE : int = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = image_processor( UpperCAmelCase_ , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _A ( self : List[str] ): # Initialize image_processor SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE : Optional[Any] = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches SCREAMING_SNAKE_CASE : Tuple = "Hello" SCREAMING_SNAKE_CASE : Tuple = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=UpperCAmelCase_ , header_text=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE : Tuple = image_processor( UpperCAmelCase_ , return_tensors="pt" , max_patches=UpperCAmelCase_ , header_text=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _A ( self : Union[str, Any] ): # Initialize image_processor SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) SCREAMING_SNAKE_CASE : Optional[Any] = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE : Tuple = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE : Tuple = image_processor( UpperCAmelCase_ , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _A ( self : int ): # Initialize image_processor SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE : str = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE : List[Any] = image_processor( UpperCAmelCase_ , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = PixaStructImageProcessor if is_vision_available() else None def _A ( self : Any ): SCREAMING_SNAKE_CASE : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE : Union[str, Any] = 3 @property def _A ( self : List[str] ): return self.image_processor_tester.prepare_image_processor_dict() def _A ( self : Any ): SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_normalize" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_convert_rgb" ) ) def _A ( self : Any ): # Initialize image_processor SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : Tuple = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE : Optional[int] = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE : List[str] = image_processor( UpperCAmelCase_ , return_tensors="pt" , max_patches=UpperCAmelCase_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
62
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
62
1
# 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 typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''Salesforce/blip-image-captioning-base''' UpperCamelCase_ : List[str] = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) UpperCamelCase_ : str = '''image_captioner''' UpperCamelCase_ : Any = AutoModelForVisionaSeq UpperCamelCase_ : List[Any] = ['''image'''] UpperCamelCase_ : Optional[int] = ['''text'''] def __init__( self : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : str ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : "Image" ): return self.pre_processor(images=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : List[str] , UpperCAmelCase_ : int ): return self.model.generate(**UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): return self.pre_processor.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ )[0].strip()
62
import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ ( lowercase , lowercase , lowercase = 1 , lowercase = 1 , lowercase = 1.0E4 , lowercase = False , lowercase = 1.0 , ): """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even''' SCREAMING_SNAKE_CASE : Union[str, Any] = float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE : Optional[Any] = min_timescale * jnp.exp(jnp.arange(lowercase , dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE : Optional[int] = jnp.expand_dims(lowercase , 1 ) * jnp.expand_dims(lowercase , 0 ) # scale embeddings SCREAMING_SNAKE_CASE : Optional[int] = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate([jnp.cos(lowercase ), jnp.sin(lowercase )] , axis=1 ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.concatenate([jnp.sin(lowercase ), jnp.cos(lowercase )] , axis=1 ) SCREAMING_SNAKE_CASE : Tuple = jnp.reshape(lowercase , [jnp.shape(lowercase )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.silu(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(UpperCAmelCase_ ) return temb class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : bool = False UpperCamelCase_ : float = 1 @nn.compact def __call__( self : Optional[int] , UpperCAmelCase_ : int ): return get_sinusoidal_embeddings( UpperCAmelCase_ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
62
1
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) snake_case = """\ Text data. Second line of data.""" snake_case = """file""" @pytest.fixture(scope="session" ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") SCREAMING_SNAKE_CASE : Optional[int] = bytes(lowercase , "utf-8" ) with zstd.open(lowercase , "wb" ) as f: f.write(lowercase ) return path @pytest.fixture def lowerCamelCase__ ( lowercase ): """simple docstring""" with open(os.path.join(tmpfs.local_root_dir , lowercase ) , "w" ) as f: f.write(lowercase ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} SCREAMING_SNAKE_CASE : int = input_paths[compression_format] SCREAMING_SNAKE_CASE : Union[str, Any] = tmp_path / "cache" SCREAMING_SNAKE_CASE : int = DownloadConfig(cache_dir=lowercase , extract_compressed_file=lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = cached_path(lowercase , download_config=lowercase ) with open(lowercase ) as f: SCREAMING_SNAKE_CASE : Dict = f.read() with open(lowercase ) as f: SCREAMING_SNAKE_CASE : List[Any] = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = "custom_cache" SCREAMING_SNAKE_CASE : str = "custom_extracted_dir" SCREAMING_SNAKE_CASE : str = tmp_path / "custom_extracted_path" if default_extracted: SCREAMING_SNAKE_CASE : str = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , lowercase ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(lowercase ) ) SCREAMING_SNAKE_CASE : str = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE : List[str] = xz_file SCREAMING_SNAKE_CASE : int = ( DownloadConfig(extract_compressed_file=lowercase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=lowercase ) ) SCREAMING_SNAKE_CASE : Any = cached_path(lowercase , download_config=lowercase ) assert Path(lowercase ).parent.parts[-2:] == expected def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = str(Path(lowercase ).resolve() ) assert cached_path(lowercase ) == text_file # relative path SCREAMING_SNAKE_CASE : Optional[Any] = str(Path(lowercase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(lowercase ) == text_file def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(lowercase ): cached_path(lowercase ) # relative path SCREAMING_SNAKE_CASE : Optional[int] = "./__missing_file__.txt" with pytest.raises(lowercase ): cached_path(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = get_from_cache(F'''tmp://{tmpfs_file}''' ) with open(lowercase ) as f: SCREAMING_SNAKE_CASE : List[Any] = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , lowercase ) def lowerCamelCase__ ( ): """simple docstring""" with pytest.raises(lowercase ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(lowercase ): http_get("https://huggingface.co" , temp_file=lowercase ) with pytest.raises(lowercase ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(lowercase ): ftp_get("ftp://huggingface.co" , temp_file=lowercase ) with pytest.raises(lowercase ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(lowercase ): fsspec_get("s3://huggingface.co" , temp_file=lowercase ) with pytest.raises(lowercase ): fsspec_head("s3://huggingface.co" )
62
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ : Any = '''image_segmenter''' UpperCamelCase_ : int = CLIPSegForImageSegmentation UpperCamelCase_ : Optional[Any] = ['''image''', '''text'''] UpperCamelCase_ : int = ['''image'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): with torch.no_grad(): SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits return logits def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
62
1
import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any]=14 , UpperCAmelCase_ : int=7 , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Any=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Optional[int]=5 , UpperCAmelCase_ : List[Any]=4 , UpperCAmelCase_ : Dict=37 , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : int=512 , UpperCAmelCase_ : Optional[int]=16 , UpperCAmelCase_ : Optional[int]=2 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : List[str]=4 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : List[str] = parent SCREAMING_SNAKE_CASE : Tuple = batch_size SCREAMING_SNAKE_CASE : List[str] = seq_length SCREAMING_SNAKE_CASE : Union[str, Any] = is_training SCREAMING_SNAKE_CASE : Any = use_token_type_ids SCREAMING_SNAKE_CASE : Tuple = use_input_mask SCREAMING_SNAKE_CASE : Any = use_labels SCREAMING_SNAKE_CASE : Tuple = use_mc_token_ids SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_act SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size SCREAMING_SNAKE_CASE : str = type_sequence_label_size SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : str = num_labels SCREAMING_SNAKE_CASE : int = num_choices SCREAMING_SNAKE_CASE : Dict = scope SCREAMING_SNAKE_CASE : str = self.vocab_size - 1 def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : str = None if self.use_mc_token_ids: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : Dict = self.get_config() SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def _A ( self : Optional[int] ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any] , *UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : str = CTRLModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , head_mask=UpperCAmelCase_ ) model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , *UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[int] = CTRLLMHeadModel(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : int = 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 : Optional[Any] ): SCREAMING_SNAKE_CASE : Tuple = 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 ) , ) : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE : Dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask} return config, inputs_dict def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple , *UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Dict = CTRLForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () UpperCamelCase_ : Any = (CTRLLMHeadModel,) if is_torch_available() else () UpperCamelCase_ : Dict = ( { '''feature-extraction''': CTRLModel, '''text-classification''': CTRLForSequenceClassification, '''text-generation''': CTRLLMHeadModel, '''zero-shot''': CTRLForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase_ : List[str] = True UpperCamelCase_ : Optional[Any] = False UpperCamelCase_ : List[str] = False def _A ( self : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def _A ( self : str ): SCREAMING_SNAKE_CASE : Union[str, Any] = CTRLModelTester(self ) SCREAMING_SNAKE_CASE : Any = ConfigTester(self , config_class=UpperCAmelCase_ , n_embd=37 ) def _A ( self : Dict ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*UpperCAmelCase_ ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _A ( self : int ): pass @slow def _A ( self : Any ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Any = CTRLModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @unittest.skip("The model doesn't support left padding" ) # and it's not used enough to be worth fixing :) def _A ( self : Dict ): pass @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Union[str, Any] ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Dict = CTRLLMHeadModel.from_pretrained("ctrl" ) model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [[1_1859, 0, 1611, 8]] , dtype=torch.long , device=UpperCAmelCase_ ) # Legal the president is SCREAMING_SNAKE_CASE : List[str] = [ 1_1859, 0, 1611, 8, 5, 150, 2_6449, 2, 19, 348, 469, 3, 2595, 48, 2_0740, 24_6533, 24_6533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a SCREAMING_SNAKE_CASE : str = model.generate(UpperCAmelCase_ , do_sample=UpperCAmelCase_ ) self.assertListEqual(output_ids[0].tolist() , UpperCAmelCase_ )
62
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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BlenderbotSmallTokenizer UpperCamelCase_ : int = False def _A ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] SCREAMING_SNAKE_CASE : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : List[Any] , **UpperCAmelCase_ : str ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : int = "adapt act apte" return input_text, output_text def _A ( self : str ): SCREAMING_SNAKE_CASE : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : List[str] = ["adapt", "act", "ap@@", "te"] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1384] SCREAMING_SNAKE_CASE : str = "I am a small frog." SCREAMING_SNAKE_CASE : List[Any] = tok([src_text] , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : int = tok.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) SCREAMING_SNAKE_CASE : Tuple = "I am a small frog ." SCREAMING_SNAKE_CASE : Optional[int] = "." SCREAMING_SNAKE_CASE : Dict = tok(UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : Optional[Any] = tok(UpperCAmelCase_ )["input_ids"] assert encoded[-1] == encoded_dot[0]
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertConfig""", """ConvBertOnnxConfig"""], """tokenization_convbert""": ["""ConvBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = ["""ConvBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """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: snake_case = [ """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 snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] snake_case = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = torch.load(lowercase , map_location="cpu" ) return sd def lowerCamelCase__ ( lowercase , lowercase , lowercase=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE : Union[str, Any] = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE : Any = new_key.replace(name_pair[0] , name_pair[1] ) SCREAMING_SNAKE_CASE : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE : Union[str, Any] = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = "pretraining" if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Any = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 512} SCREAMING_SNAKE_CASE : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = {"visual_embedding_dim": 2048} SCREAMING_SNAKE_CASE : str = "vqa_advanced" elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Tuple = {"visual_embedding_dim": 2048, "num_labels": 3129} SCREAMING_SNAKE_CASE : Optional[Any] = "vqa" elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = { "visual_embedding_dim": 1024, "num_labels": 2, } SCREAMING_SNAKE_CASE : Tuple = "nlvr" SCREAMING_SNAKE_CASE : List[Any] = VisualBertConfig(**lowercase ) # Load State Dict SCREAMING_SNAKE_CASE : List[str] = load_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Any = get_new_dict(lowercase , lowercase ) if model_type == "pretraining": SCREAMING_SNAKE_CASE : int = VisualBertForPreTraining(lowercase ) elif model_type == "vqa": SCREAMING_SNAKE_CASE : Tuple = VisualBertForQuestionAnswering(lowercase ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE : List[Any] = VisualBertForVisualReasoning(lowercase ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE : Optional[Any] = VisualBertForMultipleChoice(lowercase ) model.load_state_dict(lowercase ) # Save Checkpoints Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
62
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case = { """configuration_vivit""": ["""VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VivitConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = ["""VivitImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """VivitModel""", """VivitPreTrainedModel""", """VivitForVideoClassification""", ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """JukeboxPriorConfig""", """JukeboxVQVAEConfig""", ], """tokenization_jukebox""": ["""JukeboxTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """JukeboxModel""", """JukeboxPreTrainedModel""", """JukeboxVQVAE""", """JukeboxPrior""", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
1
from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : Any = data SCREAMING_SNAKE_CASE : Optional[int] = None def __repr__( self : List[Any] ): return f'''Node({self.data})''' class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = None def __iter__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = self.head while node: yield node.data SCREAMING_SNAKE_CASE : Optional[int] = node.next def __len__( self : str ): return sum(1 for _ in self ) def __repr__( self : str ): return "->".join([str(UpperCAmelCase_ ) for item in self] ) def __getitem__( self : List[Any] , UpperCAmelCase_ : int ): if not 0 <= index < len(self ): raise ValueError("list index out of range." ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Any ): if not 0 <= index < len(self ): raise ValueError("list index out of range." ) SCREAMING_SNAKE_CASE : Any = self.head for _ in range(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[str] = current.next SCREAMING_SNAKE_CASE : Union[str, Any] = data def _A ( self : Tuple , UpperCAmelCase_ : Any ): self.insert_nth(len(self ) , UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Any ): self.insert_nth(0 , UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Any ): if not 0 <= index <= len(self ): raise IndexError("list index out of range" ) SCREAMING_SNAKE_CASE : int = Node(UpperCAmelCase_ ) if self.head is None: SCREAMING_SNAKE_CASE : int = new_node elif index == 0: SCREAMING_SNAKE_CASE : List[Any] = self.head # link new_node to head SCREAMING_SNAKE_CASE : int = new_node else: SCREAMING_SNAKE_CASE : List[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Optional[Any] = temp.next SCREAMING_SNAKE_CASE : List[str] = temp.next SCREAMING_SNAKE_CASE : str = new_node def _A ( self : int ): # print every node data print(self ) def _A ( self : Optional[Any] ): return self.delete_nth(0 ) def _A ( self : str ): # delete from tail return self.delete_nth(len(self ) - 1 ) def _A ( self : List[str] , UpperCAmelCase_ : int = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("List index out of range." ) SCREAMING_SNAKE_CASE : Dict = self.head # default first node if index == 0: SCREAMING_SNAKE_CASE : List[str] = self.head.next else: SCREAMING_SNAKE_CASE : Any = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : List[Any] = temp.next SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : Dict = temp.next.next return delete_node.data def _A ( self : Any ): return self.head is None def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : Any = self.head while current: # Store the current node's next node. SCREAMING_SNAKE_CASE : int = current.next # Make the current node's next point backwards SCREAMING_SNAKE_CASE : Optional[int] = prev # Make the previous node be the current node SCREAMING_SNAKE_CASE : Optional[int] = current # Make the current node the next node (to progress iteration) SCREAMING_SNAKE_CASE : Optional[int] = next_node # Return prev in order to put the head at the end SCREAMING_SNAKE_CASE : str = prev def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = LinkedList() assert linked_list.is_empty() is True assert str(lowercase ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowercase ) == i linked_list.insert_nth(lowercase , i + 1 ) assert str(lowercase ) == "->".join(str(lowercase ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowercase ) == "->".join(str(lowercase ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowercase ) == 9 assert str(lowercase ) == "->".join(str(lowercase ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): SCREAMING_SNAKE_CASE : Optional[int] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowercase ) == "->".join(str(lowercase ) for i in range(-8 , 1 ) ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [ -9, 100, Node(77345112 ), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10 ), None, None, 12.20, ] SCREAMING_SNAKE_CASE : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(lowercase ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowercase ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head SCREAMING_SNAKE_CASE : str = linked_list.delete_head() assert result == -9 assert ( str(lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail SCREAMING_SNAKE_CASE : List[str] = linked_list.delete_tail() assert result == 12.2 assert ( str(lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list SCREAMING_SNAKE_CASE : Union[str, Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!" ) ) assert ( str(lowercase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowercase ) assert ( str(lowercase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowercase ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def lowerCamelCase__ ( ): """simple docstring""" from doctest import testmod testmod() SCREAMING_SNAKE_CASE : Optional[Any] = LinkedList() linked_list.insert_head(input("Inserting 1st at head " ).strip() ) linked_list.insert_head(input("Inserting 2nd at head " ).strip() ) print("\nPrint list:" ) linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail " ).strip() ) linked_list.insert_tail(input("Inserting 2nd at tail " ).strip() ) print("\nPrint list:" ) linked_list.print_list() print("\nDelete head" ) linked_list.delete_head() print("Delete tail" ) linked_list.delete_tail() print("\nPrint list:" ) linked_list.print_list() print("\nReverse linked list" ) linked_list.reverse() print("\nPrint list:" ) linked_list.print_list() print("\nString representation of linked list:" ) print(lowercase ) print("\nReading/changing Node data using indexing:" ) print(F'''Element at Position 1: {linked_list[1]}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = input("Enter New Value: " ).strip() print("New list:" ) print(lowercase ) print(F'''length of linked_list is : {len(lowercase )}''' ) if __name__ == "__main__": main()
62
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ snake_case = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ snake_case = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _A ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def _A ( self : List[Any] , UpperCAmelCase_ : List[List[List[str]]] , UpperCAmelCase_ : List[List[str]] , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCAmelCase_ , hypotheses=UpperCAmelCase_ , min_len=UpperCAmelCase_ , max_len=UpperCAmelCase_ ) }
62
1
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import sys import transformers snake_case = """3""" print("""Python version:""", sys.version) print("""transformers version:""", transformers.__version__) try: import torch print("""Torch version:""", torch.__version__) print("""Cuda available:""", torch.cuda.is_available()) print("""Cuda version:""", torch.version.cuda) print("""CuDNN version:""", torch.backends.cudnn.version()) print("""Number of GPUs available:""", torch.cuda.device_count()) print("""NCCL version:""", torch.cuda.nccl.version()) except ImportError: print("""Torch version:""", None) try: import deepspeed print("""DeepSpeed version:""", deepspeed.__version__) except ImportError: print("""DeepSpeed version:""", None) try: import tensorflow as tf print("""TensorFlow version:""", tf.__version__) print("""TF GPUs available:""", bool(tf.config.list_physical_devices("""GPU"""))) print("""Number of TF GPUs available:""", len(tf.config.list_physical_devices("""GPU"""))) except ImportError: print("""TensorFlow version:""", None)
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = row, column SCREAMING_SNAKE_CASE : Optional[Any] = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE : Optional[Any] = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = f'''%{max_element_length}s''' # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE : Optional[int] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Dict ): return str(self ) def _A ( self : Optional[int] , UpperCAmelCase_ : tuple[int, int] ): if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase_ : tuple[int, int] ): assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : int , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ): assert self.validate_indicies(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : Any = self[r, c] + another[r, c] return result def __neg__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ): return self + (-another) def __mul__( self : Dict , UpperCAmelCase_ : int | float | Matrix ): if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE : Any = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE : List[str] = f'''Unsupported type given for another ({type(UpperCAmelCase_ )})''' raise TypeError(UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : List[str] = self[r, c] return result def _A ( self : Union[str, Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE : Tuple = v.transpose() SCREAMING_SNAKE_CASE : int = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE : str = 1 print(F'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE : Optional[int] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 2, -3 SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase , lowercase )}''' ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() testa()
62
1
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 snake_case = [ """openmmlab/upernet-convnext-tiny""", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring snake_case = """UperNetConfig""" class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , 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__() SCREAMING_SNAKE_CASE : str = nn.Convad( in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , kernel_size=UpperCAmelCase_ , padding=UpperCAmelCase_ , bias=UpperCAmelCase_ , dilation=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.BatchNormad(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = nn.ReLU() def _A ( self : Union[str, Any] , UpperCAmelCase_ : torch.Tensor ): SCREAMING_SNAKE_CASE : Any = self.conv(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.batch_norm(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.activation(UpperCAmelCase_ ) return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int ): super().__init__() SCREAMING_SNAKE_CASE : str = [ nn.AdaptiveAvgPoolad(UpperCAmelCase_ ), UperNetConvModule(UpperCAmelCase_ , UpperCAmelCase_ , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Any , UpperCAmelCase_ : torch.Tensor ): SCREAMING_SNAKE_CASE : Optional[int] = input for layer in self.layers: SCREAMING_SNAKE_CASE : Optional[Any] = layer(UpperCAmelCase_ ) return hidden_state class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , UpperCAmelCase_ : Tuple[int, ...] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : bool ): super().__init__() SCREAMING_SNAKE_CASE : Dict = pool_scales SCREAMING_SNAKE_CASE : Optional[int] = align_corners SCREAMING_SNAKE_CASE : Union[str, Any] = in_channels SCREAMING_SNAKE_CASE : List[str] = channels SCREAMING_SNAKE_CASE : str = [] for i, pool_scale in enumerate(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = UperNetPyramidPoolingBlock(pool_scale=UpperCAmelCase_ , in_channels=UpperCAmelCase_ , channels=UpperCAmelCase_ ) self.blocks.append(UpperCAmelCase_ ) self.add_module(str(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : torch.Tensor ): SCREAMING_SNAKE_CASE : List[Any] = [] for ppm in self.blocks: SCREAMING_SNAKE_CASE : Dict = ppm(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = 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 ): '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ): super().__init__() SCREAMING_SNAKE_CASE : Tuple = config SCREAMING_SNAKE_CASE : List[str] = config.pool_scales # e.g. (1, 2, 3, 6) SCREAMING_SNAKE_CASE : Dict = in_channels SCREAMING_SNAKE_CASE : str = config.hidden_size SCREAMING_SNAKE_CASE : str = False SCREAMING_SNAKE_CASE : Any = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module SCREAMING_SNAKE_CASE : Tuple = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) SCREAMING_SNAKE_CASE : Tuple = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module SCREAMING_SNAKE_CASE : Union[str, Any] = nn.ModuleList() SCREAMING_SNAKE_CASE : List[Any] = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer SCREAMING_SNAKE_CASE : Optional[Any] = UperNetConvModule(UpperCAmelCase_ , self.channels , kernel_size=1 ) SCREAMING_SNAKE_CASE : Dict = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(UpperCAmelCase_ ) self.fpn_convs.append(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def _A ( self : Optional[int] ): self.apply(self._init_weights ) def _A ( self : Tuple , UpperCAmelCase_ : Union[str, 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 _A ( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Any = inputs[-1] SCREAMING_SNAKE_CASE : Union[str, Any] = [x] psp_outs.extend(self.psp_modules(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat(UpperCAmelCase_ , dim=1 ) SCREAMING_SNAKE_CASE : Optional[Any] = self.bottleneck(UpperCAmelCase_ ) return output def _A ( self : Dict , UpperCAmelCase_ : torch.Tensor ): # build laterals SCREAMING_SNAKE_CASE : Tuple = [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 SCREAMING_SNAKE_CASE : Union[str, Any] = len(UpperCAmelCase_ ) for i in range(used_backbone_levels - 1 , 0 , -1 ): SCREAMING_SNAKE_CASE : Optional[int] = laterals[i - 1].shape[2:] SCREAMING_SNAKE_CASE : List[str] = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=UpperCAmelCase_ , mode="bilinear" , align_corners=self.align_corners ) # build outputs SCREAMING_SNAKE_CASE : Any = [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 ): SCREAMING_SNAKE_CASE : List[Any] = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(UpperCAmelCase_ , dim=1 ) SCREAMING_SNAKE_CASE : Tuple = self.fpn_bottleneck(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.classifier(UpperCAmelCase_ ) return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : Union[int, Tuple[int, int]] = 1 ): super().__init__() SCREAMING_SNAKE_CASE : int = config SCREAMING_SNAKE_CASE : Optional[Any] = config.auxiliary_in_channels SCREAMING_SNAKE_CASE : List[str] = config.auxiliary_channels SCREAMING_SNAKE_CASE : List[Any] = config.auxiliary_num_convs SCREAMING_SNAKE_CASE : Tuple = config.auxiliary_concat_input SCREAMING_SNAKE_CASE : Optional[int] = in_index SCREAMING_SNAKE_CASE : List[Any] = (kernel_size // 2) * dilation SCREAMING_SNAKE_CASE : int = [] 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: SCREAMING_SNAKE_CASE : Optional[int] = nn.Identity() else: SCREAMING_SNAKE_CASE : List[str] = nn.Sequential(*UpperCAmelCase_ ) if self.concat_input: SCREAMING_SNAKE_CASE : Dict = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=UpperCAmelCase_ , padding=kernel_size // 2 ) SCREAMING_SNAKE_CASE : Optional[Any] = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def _A ( self : Optional[int] ): self.apply(self._init_weights ) def _A ( self : int , UpperCAmelCase_ : Union[str, 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 _A ( self : Tuple , UpperCAmelCase_ : torch.Tensor ): # just take the relevant feature maps SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_hidden_states[self.in_index] SCREAMING_SNAKE_CASE : Any = self.convs(UpperCAmelCase_ ) if self.concat_input: SCREAMING_SNAKE_CASE : str = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) SCREAMING_SNAKE_CASE : int = self.classifier(UpperCAmelCase_ ) return output class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = UperNetConfig UpperCamelCase_ : List[str] = '''pixel_values''' UpperCamelCase_ : List[str] = True def _A ( self : Tuple , UpperCAmelCase_ : Tuple ): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def _A ( self : Tuple ): self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def _A ( self : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict=False ): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = value snake_case = r""" Parameters: This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. config ([`UperNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ snake_case = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.''' , lowerCAmelCase , ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : Any ): super().__init__(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) SCREAMING_SNAKE_CASE : Union[str, Any] = UperNetHead(UpperCAmelCase_ , in_channels=self.backbone.channels ) SCREAMING_SNAKE_CASE : Union[str, Any] = 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 _A ( self : Union[str, Any] , UpperCAmelCase_ : Optional[torch.Tensor] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[torch.Tensor] = None , UpperCAmelCase_ : Optional[bool] = None , ): SCREAMING_SNAKE_CASE : int = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[Any] = output_attentions if output_attentions is not None else self.config.output_attentions SCREAMING_SNAKE_CASE : Tuple = self.backbone.forward_with_filtered_kwargs( UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , output_attentions=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.feature_maps SCREAMING_SNAKE_CASE : Optional[Any] = self.decode_head(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = nn.functional.interpolate(UpperCAmelCase_ , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = None if self.auxiliary_head is not None: SCREAMING_SNAKE_CASE : Dict = self.auxiliary_head(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = nn.functional.interpolate( UpperCAmelCase_ , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = 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 SCREAMING_SNAKE_CASE : Optional[Any] = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) SCREAMING_SNAKE_CASE : Dict = loss_fct(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = loss_fct(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: SCREAMING_SNAKE_CASE : Any = (logits,) + outputs[1:] else: SCREAMING_SNAKE_CASE : Any = (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 , )
62
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } snake_case = { """junnyu/roformer_chinese_small""": 1_536, """junnyu/roformer_chinese_base""": 1_536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } snake_case = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = RoFormerTokenizer def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : List[str]="[UNK]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : Any="[PAD]" , UpperCAmelCase_ : List[str]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : List[str] , ): 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_ , ) SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase_ ) != strip_accents ): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : List[str] = strip_accents SCREAMING_SNAKE_CASE : Tuple = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : Tuple , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = d SCREAMING_SNAKE_CASE : Dict = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE : Any = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase_ ) ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _A ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : List[Any] = [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 _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Optional[int] = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
62
1
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case = datasets.load_iris() snake_case = np.array(data["""data"""]) snake_case = np.array(data["""target"""]) snake_case = data["""target_names"""] snake_case , snake_case , snake_case , snake_case = train_test_split(X, y) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase=5 ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = zip(lowercase , lowercase ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE : Optional[int] = [] for data_point in data: SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE : List[Any] = [i[1] for i in sorted(lowercase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE : List[Any] = Counter(lowercase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
62
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE : Optional[int] = str(abs(lowercase ) ) SCREAMING_SNAKE_CASE : str = [list(lowercase ) for char in range(len(lowercase ) )] for index in range(len(lowercase ) ): num_transpositions[index].pop(lowercase ) return max( int("".join(list(lowercase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
62
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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BlenderbotSmallTokenizer UpperCamelCase_ : int = False def _A ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] SCREAMING_SNAKE_CASE : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : List[Any] , **UpperCAmelCase_ : str ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : int = "adapt act apte" return input_text, output_text def _A ( self : str ): SCREAMING_SNAKE_CASE : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : List[str] = ["adapt", "act", "ap@@", "te"] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1384] SCREAMING_SNAKE_CASE : str = "I am a small frog." SCREAMING_SNAKE_CASE : List[Any] = tok([src_text] , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : int = tok.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) SCREAMING_SNAKE_CASE : Tuple = "I am a small frog ." SCREAMING_SNAKE_CASE : Optional[int] = "." SCREAMING_SNAKE_CASE : Dict = tok(UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : Optional[Any] = tok(UpperCAmelCase_ )["input_ids"] assert encoded[-1] == encoded_dot[0]
62
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = 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 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : int ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) 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 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _A ( self : Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9E-2
62
1
from __future__ import annotations snake_case = 1.6021e-19 # units = C def lowerCamelCase__ ( lowercase , lowercase , lowercase , ): """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif conductivity < 0: raise ValueError("Conductivity cannot be negative" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative" ) elif mobility < 0: raise ValueError("mobility cannot be negative" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
62
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 ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE : List[Any] = [144, 192, 240] SCREAMING_SNAKE_CASE : Tuple = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [96, 120, 144] SCREAMING_SNAKE_CASE : Dict = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [64, 80, 96] SCREAMING_SNAKE_CASE : List[str] = [16, 16, 24, 48, 64, 80, 320] SCREAMING_SNAKE_CASE : int = 0.05 SCREAMING_SNAKE_CASE : int = 2.0 if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : str = 512 SCREAMING_SNAKE_CASE : List[str] = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 21 SCREAMING_SNAKE_CASE : Dict = "pascal-voc-id2label.json" else: SCREAMING_SNAKE_CASE : Optional[Any] = 1000 SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : Any = "huggingface/label-files" SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowercase , lowercase , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE : List[str] = {int(lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} return config def lowerCamelCase__ ( lowercase , lowercase=False ): """simple docstring""" for i in range(1 , 6 ): if F'''layer_{i}.''' in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(F'''layer_{i}.''' , F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: SCREAMING_SNAKE_CASE : Dict = name.replace("conv_1." , "conv_stem." ) if ".block." in name: SCREAMING_SNAKE_CASE : List[str] = name.replace(".block." , "." ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE : str = name.replace("exp_1x1" , "expand_1x1" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("red_1x1" , "reduce_1x1" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".local_rep.conv_3x3." , ".conv_kxk." ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE : int = name.replace(".local_rep.conv_1x1." , ".conv_1x1." ) if ".norm." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".norm." , ".normalization." ) if ".conv." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".conv." , ".convolution." ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".conv_proj." , ".conv_projection." ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.layer.{j}.''' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.''' ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("expand_1x1" , "downsampling_layer.expand_1x1" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE : str = name.replace("conv_3x3" , "downsampling_layer.conv_3x3" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("reduce_1x1" , "downsampling_layer.reduce_1x1" ) for i in range(2 , 5 ): if F'''.global_rep.{i}.weight''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.global_rep.{i}.weight''' , ".layernorm.weight" ) if F'''.global_rep.{i}.bias''' in name: SCREAMING_SNAKE_CASE : str = name.replace(F'''.global_rep.{i}.bias''' , ".layernorm.bias" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".global_rep." , ".transformer." ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_mha.0." , ".layernorm_before." ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_mha.1.out_proj." , ".attention.output.dense." ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(".pre_norm_ffn.0." , ".layernorm_after." ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_ffn.1." , ".intermediate.dense." ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_ffn.4." , ".output.dense." ) if ".transformer." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".transformer." , ".transformer.layer." ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE : int = name.replace(".aspp_layer." , "." ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".aspp_pool." , "." ) if "seg_head." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("seg_head." , "segmentation_head." ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("segmentation_head.classifier.classifier." , "segmentation_head.classifier." ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("classifier.fc." , "classifier." ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE : List[Any] = "mobilevit." + name return name def lowerCamelCase__ ( lowercase , lowercase , lowercase=False ): """simple docstring""" if base_model: SCREAMING_SNAKE_CASE : Optional[int] = "" else: SCREAMING_SNAKE_CASE : Any = "mobilevit." for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = orig_state_dict.pop(lowercase ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE : int = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.split("." ) SCREAMING_SNAKE_CASE : Any = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE : List[Any] = int(key_split[3] ) SCREAMING_SNAKE_CASE : List[Any] = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) SCREAMING_SNAKE_CASE : int = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE : Union[str, Any] = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: SCREAMING_SNAKE_CASE : str = val[:dim] SCREAMING_SNAKE_CASE : Union[str, Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] else: SCREAMING_SNAKE_CASE : List[Any] = val return orig_state_dict def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_mobilevit_config(lowercase ) # load original state_dict SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(lowercase , map_location="cpu" ) # load 🤗 model if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : List[str] = MobileViTForSemanticSegmentation(lowercase ).eval() else: SCREAMING_SNAKE_CASE : str = MobileViTForImageClassification(lowercase ).eval() SCREAMING_SNAKE_CASE : Any = convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE : List[Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE : List[Any] = model(**lowercase ) SCREAMING_SNAKE_CASE : str = outputs.logits if mobilevit_name.startswith("deeplabv3_" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] , lowercase , atol=1E-4 ) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE : Dict = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] , lowercase , atol=1E-4 ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if push_to_hub: SCREAMING_SNAKE_CASE : List[str] = { "mobilevit_s": "mobilevit-small", "mobilevit_xs": "mobilevit-x-small", "mobilevit_xxs": "mobilevit-xx-small", "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small", "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small", "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small", } print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE : int = model_mapping[mobilevit_name] image_processor.push_to_hub(lowercase , organization="apple" ) model.push_to_hub(lowercase , organization="apple" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, 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 = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
62
1
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = os.path.join(args.tf_model_dir , "parameters.json" ) SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(open(lowercase ).read() ) if not params: raise ValueError( F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.''' ) if not args.output.endswith(".pt" ): SCREAMING_SNAKE_CASE : Optional[int] = args.output + ".pt" SCREAMING_SNAKE_CASE : Any = OrderedDict() with tf.device("/CPU:0" ): SCREAMING_SNAKE_CASE : Union[str, Any] = tf.train.load_checkpoint(args.tf_model_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): SCREAMING_SNAKE_CASE : Any = reader.get_tensor(lowercase ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9] ) elif key_name.startswith("pasts/out" ): SCREAMING_SNAKE_CASE : Optional[int] = 8 SCREAMING_SNAKE_CASE : List[Any] = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time SCREAMING_SNAKE_CASE : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.startswith("model/moe" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/softmlp/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): SCREAMING_SNAKE_CASE : Optional[int] = key_name[-9:-7] for i in range(16 ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) SCREAMING_SNAKE_CASE : List[str] = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name.startswith("model/mlp" ): SCREAMING_SNAKE_CASE : str = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.mlp.wi.weight" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/p1/bias" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.wi.bias" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/kernel" ): SCREAMING_SNAKE_CASE : str = "model.blocks.%d.feed_forward.mlp.wo.weight" % player SCREAMING_SNAKE_CASE : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/bias" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.feed_forward.mlp.wo.bias" % player SCREAMING_SNAKE_CASE : str = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) elif key_name.startswith("model/ln" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.norm.bias" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : List[str] = "model.blocks.%d.feed_forward.norm.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/att" ): SCREAMING_SNAKE_CASE : Optional[int] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum SCREAMING_SNAKE_CASE : List[str] = state[:, 0, :, :] SCREAMING_SNAKE_CASE : Tuple = state[:, 1, :, :] SCREAMING_SNAKE_CASE : List[Any] = state[:, 2, :, :] SCREAMING_SNAKE_CASE : Tuple = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : int = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/o/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif key_name.startswith("model/an" ): SCREAMING_SNAKE_CASE : int = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.self_attn.norm.bias" % player SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.self_attn.norm.weight" % player SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): SCREAMING_SNAKE_CASE : str = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] SCREAMING_SNAKE_CASE : List[str] = "model.%s.weight" % nlayer SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) if key_name.startswith("model/wte" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "lm_head.weight" SCREAMING_SNAKE_CASE : List[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/wob" ): SCREAMING_SNAKE_CASE : List[Any] = "final_logits_bias" SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : List[str] = state.reshape((1, -1) ) SCREAMING_SNAKE_CASE : int = torch.tensor(lowercase ) elif key_name == "model/dense/kernel": SCREAMING_SNAKE_CASE : Optional[int] = "model.last_project.weight" SCREAMING_SNAKE_CASE : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name == "model/dense_1/bias": SCREAMING_SNAKE_CASE : str = "model.last_project.bias" SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) torch.save(lowercase , args.output ) if __name__ == "__main__": snake_case = argparse.ArgumentParser( description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""") parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""") snake_case = parser.parse_args() convert_tf_gptsan_to_pt(args)
62
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case = datasets.load_iris() snake_case = np.array(data["""data"""]) snake_case = np.array(data["""target"""]) snake_case = data["""target_names"""] snake_case , snake_case , snake_case , snake_case = train_test_split(X, y) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase=5 ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = zip(lowercase , lowercase ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE : Optional[int] = [] for data_point in data: SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE : List[Any] = [i[1] for i in sorted(lowercase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE : List[Any] = Counter(lowercase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
62
1
def lowerCamelCase__ ( lowercase = 600851475143 ): """simple docstring""" try: SCREAMING_SNAKE_CASE : Tuple = int(lowercase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : Optional[int] = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE : Tuple = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE : int = n return int(lowercase ) if __name__ == "__main__": print(F"""{solution() = }""")
62
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''xlm-prophetnet''' UpperCamelCase_ : Tuple = ['''past_key_values'''] UpperCamelCase_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Dict , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[Union[str, Callable]] = "gelu" , UpperCAmelCase_ : Optional[int] = 3_0522 , UpperCAmelCase_ : Optional[int] = 1024 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[int] = 512 , UpperCAmelCase_ : Optional[float] = 0.02 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 2 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 128 , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[float] = 0.0 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 2 , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = num_encoder_layers SCREAMING_SNAKE_CASE : Any = num_encoder_attention_heads SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers SCREAMING_SNAKE_CASE : List[Any] = num_decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE : Dict = ngram SCREAMING_SNAKE_CASE : Any = num_buckets SCREAMING_SNAKE_CASE : str = relative_max_distance SCREAMING_SNAKE_CASE : str = disable_ngram_loss SCREAMING_SNAKE_CASE : Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : int = use_cache super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , add_cross_attention=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def _A ( self : int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
62
1
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate snake_case = trt.Logger(trt.Logger.WARNING) snake_case = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) snake_case = logging.getLogger(__name__) snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--onnx_model_path""", default=None, type=str, required=True, help="""Path to ONNX model: """, ) parser.add_argument( """--output_dir""", default=None, type=str, required=True, help="""The output directory where the model checkpoints and predictions will be written.""", ) # Other parameters parser.add_argument( """--tokenizer_name""", default="""""", type=str, required=True, help="""Pretrained tokenizer name or path if not the same as model_name""", ) parser.add_argument( """--version_2_with_negative""", action="""store_true""", help="""If true, the SQuAD examples contain some that do not have an answer.""", ) parser.add_argument( """--null_score_diff_threshold""", type=float, default=0.0, help="""If null_score - best_non_null is greater than the threshold predict null.""", ) parser.add_argument( """--max_seq_length""", default=384, type=int, help=( """The maximum total input sequence length after WordPiece tokenization. Sequences """ """longer than this will be truncated, and sequences shorter than this will be padded.""" ), ) parser.add_argument( """--doc_stride""", default=128, type=int, help="""When splitting up a long document into chunks, how much stride to take between chunks.""", ) parser.add_argument("""--per_device_eval_batch_size""", default=8, type=int, help="""Batch size per GPU/CPU for evaluation.""") parser.add_argument( """--n_best_size""", default=20, type=int, help="""The total number of n-best predictions to generate in the nbest_predictions.json output file.""", ) parser.add_argument( """--max_answer_length""", default=30, type=int, help=( """The maximum length of an answer that can be generated. This is needed because the start """ """and end predictions are not conditioned on one another.""" ), ) parser.add_argument("""--seed""", type=int, default=42, help="""random seed for initialization""") parser.add_argument( """--dataset_name""", type=str, default=None, required=True, help="""The name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--dataset_config_name""", type=str, default=None, help="""The configuration name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--preprocessing_num_workers""", type=int, default=4, help="""A csv or a json file containing the training data.""" ) parser.add_argument("""--overwrite_cache""", action="""store_true""", help="""Overwrite the cached training and evaluation sets""") parser.add_argument( """--fp16""", action="""store_true""", help="""Whether to use 16-bit (mixed) precision instead of 32-bit""", ) parser.add_argument( """--int8""", action="""store_true""", help="""Whether to use INT8""", ) snake_case = parser.parse_args() if args.tokenizer_name: snake_case = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) logger.info("""Training/evaluation parameters %s""", args) snake_case = args.per_device_eval_batch_size snake_case = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties snake_case = True snake_case = """temp_engine/bert-fp32.engine""" if args.fpaa: snake_case = """temp_engine/bert-fp16.engine""" if args.inta: snake_case = """temp_engine/bert-int8.engine""" # import ONNX file if not os.path.exists("""temp_engine"""): os.makedirs("""temp_engine""") snake_case = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, """rb""") as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network snake_case = [network.get_input(i) for i in range(network.num_inputs)] snake_case = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: snake_case = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) snake_case = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) snake_case = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, """wb""") as f: f.write(engine.serialize()) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = np.asarray(inputs["input_ids"] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : List[Any] = np.asarray(inputs["attention_mask"] , dtype=np.intaa ) SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs["token_type_ids"] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase ) # start time SCREAMING_SNAKE_CASE : Optional[Any] = time.time() # Run inference context.execute_async( bindings=[int(lowercase ) for d_inp in d_inputs] + [int(lowercase ), int(lowercase )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase , lowercase , lowercase ) cuda.memcpy_dtoh_async(lowercase , lowercase , lowercase ) # Synchronize the stream and take time stream.synchronize() # end time SCREAMING_SNAKE_CASE : Any = time.time() SCREAMING_SNAKE_CASE : int = end_time - start_time SCREAMING_SNAKE_CASE : Tuple = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. snake_case = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError("""Evaluation requires a dataset name""") # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. snake_case = raw_datasets["""validation"""].column_names snake_case = """question""" if """question""" in column_names else column_names[0] snake_case = """context""" if """context""" in column_names else column_names[1] snake_case = """answers""" if """answers""" in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). snake_case = tokenizer.padding_side == """right""" if args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) snake_case = min(args.max_seq_length, tokenizer.model_max_length) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. SCREAMING_SNAKE_CASE : List[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation="only_second" if pad_on_right else "only_first" , max_length=lowercase , stride=args.doc_stride , return_overflowing_tokens=lowercase , return_offsets_mapping=lowercase , padding="max_length" , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. SCREAMING_SNAKE_CASE : Union[str, Any] = tokenized_examples.pop("overflow_to_sample_mapping" ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples["input_ids"] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). SCREAMING_SNAKE_CASE : Any = tokenized_examples.sequence_ids(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. SCREAMING_SNAKE_CASE : List[Any] = sample_mapping[i] tokenized_examples["example_id"].append(examples["id"][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. SCREAMING_SNAKE_CASE : str = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples["offset_mapping"][i] ) ] return tokenized_examples snake_case = raw_datasets["""validation"""] # Validation Feature Creation snake_case = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc="""Running tokenizer on validation dataset""", ) snake_case = default_data_collator snake_case = eval_dataset.remove_columns(["""example_id""", """offset_mapping"""]) snake_case = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase="eval" ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = postprocess_qa_predictions( examples=lowercase , features=lowercase , predictions=lowercase , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase , ) # Format the result to the format the metric expects. if args.version_2_with_negative: SCREAMING_SNAKE_CASE : Dict = [ {"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items() ] else: SCREAMING_SNAKE_CASE : Any = [{"id": k, "prediction_text": v} for k, v in predictions.items()] SCREAMING_SNAKE_CASE : List[Any] = [{"id": ex["id"], "answers": ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase , label_ids=lowercase ) snake_case = load_metric("""squad_v2""" if args.version_2_with_negative else """squad""") # Evaluation! logger.info("""Loading ONNX model %s for evaluation""", args.onnx_model_path) with open(engine_name, """rb""") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCamelCase__ ( lowercase ): """simple docstring""" return trt.volume(engine.get_binding_shape(lowercase ) ) * engine.get_binding_dtype(lowercase ).itemsize # Allocate device memory for inputs and outputs. snake_case = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer snake_case = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) snake_case = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) snake_case = cuda.mem_alloc(h_outputa.nbytes) snake_case = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. snake_case = cuda.Stream() # Evaluation logger.info("""***** Running Evaluation *****""") logger.info(F""" Num examples = {len(eval_dataset)}""") logger.info(F""" Batch size = {args.per_device_eval_batch_size}""") snake_case = 0.0 snake_case = 0 snake_case = timeit.default_timer() snake_case = None for step, batch in enumerate(eval_dataloader): snake_case , snake_case = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 snake_case , snake_case = outputs snake_case = torch.tensor(start_logits) snake_case = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered snake_case = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100) snake_case = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100) snake_case = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) snake_case = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if all_preds is not None: snake_case = nested_truncate(all_preds, len(eval_dataset)) snake_case = timeit.default_timer() - start_time logger.info(""" Evaluation done in total %f secs (%f sec per example)""", evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info("""Average Inference Time = {:.3f} ms""".format(total_time * 1_000 / niter)) logger.info("""Total Inference Time = {:.3f} ms""".format(total_time * 1_000)) logger.info("""Total Number of Inference = %d""", niter) snake_case = post_processing_function(eval_examples, eval_dataset, all_preds) snake_case = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(F"""Evaluation metrics: {eval_metric}""")
62
import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, 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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = KandinskyVaaPipeline UpperCamelCase_ : List[Any] = [ '''image_embeds''', '''negative_image_embeds''', ] UpperCamelCase_ : Tuple = ['''image_embeds''', '''negative_image_embeds'''] UpperCamelCase_ : Any = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCamelCase_ : List[str] = False @property def _A ( self : List[Any] ): return 32 @property def _A ( self : List[Any] ): return 32 @property def _A ( self : Any ): return self.time_input_dim @property def _A ( self : Union[str, Any] ): return self.time_input_dim * 4 @property def _A ( self : Tuple ): return 100 @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } SCREAMING_SNAKE_CASE : str = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def _A ( self : int ): 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 : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = self.dummy_unet SCREAMING_SNAKE_CASE : str = self.dummy_movq SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="epsilon" , thresholding=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _A ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]=0 ): SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = "cpu" SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : Tuple = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array( [0.6_237_976, 1.0, 0.36_441_332, 1.0, 0.70_639_634, 0.29_877_186, 0.85_652_125, 0.5_216_843, 0.54_454_046] ) 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy" ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Tuple = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = "red cat, 4k photo" SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="np" , ) SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
62
1
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm snake_case = re.compile("""[^A-Za-z_0-9]""") # parameters used in DuplicationIndex snake_case = 10 snake_case = 256 def lowerCamelCase__ ( lowercase ): """simple docstring""" if len(lowercase ) < MIN_NUM_TOKENS: return None SCREAMING_SNAKE_CASE : int = MinHash(num_perm=lowercase ) for token in set(lowercase ): min_hash.update(token.encode() ) return min_hash def lowerCamelCase__ ( lowercase ): """simple docstring""" return {t for t in NON_ALPHA.split(lowercase ) if len(t.strip() ) > 0} class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , *, UpperCAmelCase_ : float = 0.85 , ): SCREAMING_SNAKE_CASE : Tuple = duplication_jaccard_threshold SCREAMING_SNAKE_CASE : Dict = NUM_PERM SCREAMING_SNAKE_CASE : Optional[int] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) SCREAMING_SNAKE_CASE : Optional[Any] = defaultdict(UpperCAmelCase_ ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : MinHash ): SCREAMING_SNAKE_CASE : Optional[Any] = self._index.query(UpperCAmelCase_ ) if code_key in self._index.keys: print(f'''Duplicate key {code_key}''' ) return self._index.insert(UpperCAmelCase_ , UpperCAmelCase_ ) if len(UpperCAmelCase_ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(UpperCAmelCase_ ) break else: self._duplicate_clusters[close_duplicates[0]].add(UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Any = [] for base, duplicates in self._duplicate_clusters.items(): SCREAMING_SNAKE_CASE : Dict = [base] + list(UpperCAmelCase_ ) # reformat the cluster to be a list of dict SCREAMING_SNAKE_CASE : Optional[Any] = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(UpperCAmelCase_ ) return duplicate_clusters def _A ( self : int , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : Tuple = self.get_duplicate_clusters() with open(UpperCAmelCase_ , "w" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = element SCREAMING_SNAKE_CASE : str = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def lowerCamelCase__ ( lowercase ): """simple docstring""" with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowercase , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = DuplicationIndex(duplication_jaccard_threshold=lowercase ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowercase ) ) , max_queue_size=100 ) ): di.add(lowercase , lowercase ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = get_tokens(lowercase ) SCREAMING_SNAKE_CASE : int = get_tokens(lowercase ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) snake_case = None def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = [] for elementa in cluster: SCREAMING_SNAKE_CASE : str = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: SCREAMING_SNAKE_CASE : Optional[int] = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(lowercase , lowercase ) >= jaccard_threshold: elementa["copies"] += 1 break else: SCREAMING_SNAKE_CASE : Any = 1 extremes.append(lowercase ) return extremes def lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" global _shared_dataset SCREAMING_SNAKE_CASE : Optional[int] = dataset SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Any = partial(_find_cluster_extremes_shared , jaccard_threshold=lowercase ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowercase , lowercase , ) , total=len(lowercase ) , ): extremes_list.append(lowercase ) return extremes_list def lowerCamelCase__ ( lowercase , lowercase = 0.85 ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = make_duplicate_clusters(lowercase , lowercase ) SCREAMING_SNAKE_CASE : List[Any] = {x["base_index"] for cluster in duplicate_clusters for x in cluster} SCREAMING_SNAKE_CASE : Dict = {} SCREAMING_SNAKE_CASE : int = find_extremes(lowercase , lowercase , lowercase ) for extremes in extremes_clusters: for element in extremes: SCREAMING_SNAKE_CASE : Any = element SCREAMING_SNAKE_CASE : str = duplicate_indices - set(extreme_dict.keys() ) SCREAMING_SNAKE_CASE : Tuple = dataset.filter(lambda lowercase , lowercase : idx not in remove_indices , with_indices=lowercase ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: SCREAMING_SNAKE_CASE : List[str] = element["base_index"] in extreme_dict if element["is_extreme"]: SCREAMING_SNAKE_CASE : Tuple = extreme_dict[element["base_index"]]["copies"] print(F'''Original dataset size: {len(lowercase )}''' ) print(F'''Number of duplicate clusters: {len(lowercase )}''' ) print(F'''Files in duplicate cluster: {len(lowercase )}''' ) print(F'''Unique files in duplicate cluster: {len(lowercase )}''' ) print(F'''Filtered dataset size: {len(lowercase )}''' ) return ds_filter, duplicate_clusters
62
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput snake_case = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : int , *UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Tuple=None , **UpperCAmelCase_ : Optional[Any] ): super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = eval_examples SCREAMING_SNAKE_CASE : List[Any] = post_process_function SCREAMING_SNAKE_CASE : Any = quant_trainer_args SCREAMING_SNAKE_CASE : Optional[Any] = 128 # default number of calibration samples def _A ( self : Optional[Any] , UpperCAmelCase_ : Tuple=None ): if calib_dataset is None and self.calib_dataset is None: raise ValueError("Trainer: calibration requires an calib_dataset." ) SCREAMING_SNAKE_CASE : str = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE : str = self._remove_unused_columns(UpperCAmelCase_ , description="Calibration" ) return DataLoader( UpperCAmelCase_ , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=UpperCAmelCase_ , ) def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[int]=None ): SCREAMING_SNAKE_CASE : Any = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_calib_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args , calib=UpperCAmelCase_ ) model.eval() quant_trainer.enable_calibration(UpperCAmelCase_ ) logger.info("***** Running calibration *****" ) logger.info(f''' Num examples = {self.calib_num}''' ) logger.info(f''' Batch size = {calib_dataloader.batch_size}''' ) for step, inputs in enumerate(UpperCAmelCase_ ): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.prediction_step(UpperCAmelCase_ , UpperCAmelCase_ , prediction_loss_only=UpperCAmelCase_ ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : Optional[int] = model def _A ( self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str = "eval" ): SCREAMING_SNAKE_CASE : List[str] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : Tuple = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : int = eval_loop( UpperCAmelCase_ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : int = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE : List[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions ) SCREAMING_SNAKE_CASE : Any = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = metrics.pop(UpperCAmelCase_ ) self.log(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : List[Any] = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : List[str] = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCAmelCase_ ) return metrics def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : str = "test" ): SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(UpperCAmelCase_ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Tuple = self.compute_metrics SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : str = eval_loop( UpperCAmelCase_ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : Union[str, Any] = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Optional[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions , "predict" ) SCREAMING_SNAKE_CASE : str = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : str = metrics.pop(UpperCAmelCase_ ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCAmelCase_ ) def _A ( self : Any , UpperCAmelCase_ : int="./" ): SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = next(iter(UpperCAmelCase_ ) ) # saving device - to make it consistent SCREAMING_SNAKE_CASE : int = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) # convert to tuple SCREAMING_SNAKE_CASE : Tuple = tuple(v.to(UpperCAmelCase_ ) for k, v in batch.items() ) logger.info("Converting model to be onnx compatible" ) from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Any = self.model.to(UpperCAmelCase_ ) model.eval() model.float() SCREAMING_SNAKE_CASE : str = model.module if hasattr(UpperCAmelCase_ , "module" ) else model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : List[Any] = os.path.join(UpperCAmelCase_ , "model.onnx" ) logger.info(f'''exporting model to {output_model_file}''' ) SCREAMING_SNAKE_CASE : int = {0: "batch_size", 1: "seq_len"} torch.onnx.export( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , export_params=UpperCAmelCase_ , opset_version=13 , do_constant_folding=UpperCAmelCase_ , input_names=["input_ids", "attention_mask", "token_type_ids"] , output_names=["output_start_logits", "output_end_logits"] , dynamic_axes={ "input_ids": axes, "attention_mask": axes, "token_type_ids": axes, "output_start_logits": axes, "output_end_logits": axes, } , verbose=UpperCAmelCase_ , ) logger.info("onnx export finished" )
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_lilt""": ["""LILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LiltConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """LILT_PRETRAINED_MODEL_ARCHIVE_LIST""", """LiltForQuestionAnswering""", """LiltForSequenceClassification""", """LiltForTokenClassification""", """LiltModel""", """LiltPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = LayoutLMTokenizer UpperCamelCase_ : str = LayoutLMTokenizerFast UpperCamelCase_ : Any = True UpperCamelCase_ : Optional[Any] = True def _A ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : str , **UpperCAmelCase_ : Optional[int] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Any = "UNwant\u00E9d,running" SCREAMING_SNAKE_CASE : Union[str, Any] = "unwanted, running" return input_text, output_text def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [7, 4, 5, 10, 8, 9] ) def _A ( self : List[str] ): pass
62
1
def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" if height >= 1: move_tower(height - 1 , lowercase , lowercase , lowercase ) move_disk(lowercase , lowercase ) move_tower(height - 1 , lowercase , lowercase , lowercase ) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" print("moving disk from" , lowercase , "to" , lowercase ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = int(input("Height of hanoi: " ).strip() ) move_tower(lowercase , "A" , "B" , "C" ) if __name__ == "__main__": main()
62
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = os.path.join(args.tf_model_dir , "parameters.json" ) SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(open(lowercase ).read() ) if not params: raise ValueError( F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.''' ) if not args.output.endswith(".pt" ): SCREAMING_SNAKE_CASE : Optional[int] = args.output + ".pt" SCREAMING_SNAKE_CASE : Any = OrderedDict() with tf.device("/CPU:0" ): SCREAMING_SNAKE_CASE : Union[str, Any] = tf.train.load_checkpoint(args.tf_model_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): SCREAMING_SNAKE_CASE : Any = reader.get_tensor(lowercase ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9] ) elif key_name.startswith("pasts/out" ): SCREAMING_SNAKE_CASE : Optional[int] = 8 SCREAMING_SNAKE_CASE : List[Any] = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time SCREAMING_SNAKE_CASE : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.startswith("model/moe" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/softmlp/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): SCREAMING_SNAKE_CASE : Optional[int] = key_name[-9:-7] for i in range(16 ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) SCREAMING_SNAKE_CASE : List[str] = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name.startswith("model/mlp" ): SCREAMING_SNAKE_CASE : str = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.mlp.wi.weight" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/p1/bias" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.wi.bias" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/kernel" ): SCREAMING_SNAKE_CASE : str = "model.blocks.%d.feed_forward.mlp.wo.weight" % player SCREAMING_SNAKE_CASE : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/bias" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.feed_forward.mlp.wo.bias" % player SCREAMING_SNAKE_CASE : str = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) elif key_name.startswith("model/ln" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.norm.bias" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : List[str] = "model.blocks.%d.feed_forward.norm.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/att" ): SCREAMING_SNAKE_CASE : Optional[int] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum SCREAMING_SNAKE_CASE : List[str] = state[:, 0, :, :] SCREAMING_SNAKE_CASE : Tuple = state[:, 1, :, :] SCREAMING_SNAKE_CASE : List[Any] = state[:, 2, :, :] SCREAMING_SNAKE_CASE : Tuple = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : int = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/o/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif key_name.startswith("model/an" ): SCREAMING_SNAKE_CASE : int = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.self_attn.norm.bias" % player SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.self_attn.norm.weight" % player SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): SCREAMING_SNAKE_CASE : str = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] SCREAMING_SNAKE_CASE : List[str] = "model.%s.weight" % nlayer SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) if key_name.startswith("model/wte" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "lm_head.weight" SCREAMING_SNAKE_CASE : List[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/wob" ): SCREAMING_SNAKE_CASE : List[Any] = "final_logits_bias" SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : List[str] = state.reshape((1, -1) ) SCREAMING_SNAKE_CASE : int = torch.tensor(lowercase ) elif key_name == "model/dense/kernel": SCREAMING_SNAKE_CASE : Optional[int] = "model.last_project.weight" SCREAMING_SNAKE_CASE : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name == "model/dense_1/bias": SCREAMING_SNAKE_CASE : str = "model.last_project.bias" SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) torch.save(lowercase , args.output ) if __name__ == "__main__": snake_case = argparse.ArgumentParser( description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""") parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""") snake_case = parser.parse_args() convert_tf_gptsan_to_pt(args)
62
1
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = LayoutLMTokenizer UpperCamelCase_ : str = LayoutLMTokenizerFast UpperCamelCase_ : Any = True UpperCamelCase_ : Optional[Any] = True def _A ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : str , **UpperCAmelCase_ : Optional[int] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Any = "UNwant\u00E9d,running" SCREAMING_SNAKE_CASE : Union[str, Any] = "unwanted, running" return input_text, output_text def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [7, 4, 5, 10, 8, 9] ) def _A ( self : List[str] ): pass
62
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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: on SCREAMING_SNAKE_CASE : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Optional[int] = { "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], } SCREAMING_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 _A ( self : List[Any] , **UpperCAmelCase_ : List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Union[str, Any] , **UpperCAmelCase_ : Any ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Union[str, Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE : Any = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) SCREAMING_SNAKE_CASE : str = 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 _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : int = image_processor(UpperCAmelCase_ , return_tensors="np" ) SCREAMING_SNAKE_CASE : Optional[int] = 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 _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = "lower newer" SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : int = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = "lower newer" SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Optional[Any] = processor.batch_decode(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = "lower newer" SCREAMING_SNAKE_CASE : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
62
1
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """allegro/herbert-base-cased""": """https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json""" }, """merges_file""": { """allegro/herbert-base-cased""": """https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt""" }, } snake_case = {"""allegro/herbert-base-cased""": 514} snake_case = {} class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = VOCAB_FILES_NAMES UpperCamelCase_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = HerbertTokenizer def __init__( self : List[str] , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : Optional[Any]="<unk>" , UpperCAmelCase_ : Optional[int]="<pad>" , UpperCAmelCase_ : Union[str, Any]="<mask>" , UpperCAmelCase_ : int="</s>" , **UpperCAmelCase_ : List[Any] , ): super().__init__( UpperCAmelCase_ , UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , **UpperCAmelCase_ , ) def _A ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : Optional[Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE : Optional[int] = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _A ( self : Optional[Any] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] def _A ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Tuple = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ )
62
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "tf_padding" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "depth_multiplier" ) ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]=13 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : int=0.25 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : Dict=8 , UpperCAmelCase_ : Optional[int]=6 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : str="relu6" , UpperCAmelCase_ : List[str]=1280 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : int = depth_multiplier SCREAMING_SNAKE_CASE : str = depth_divisible_by SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth SCREAMING_SNAKE_CASE : int = expand_ratio SCREAMING_SNAKE_CASE : Tuple = tf_padding SCREAMING_SNAKE_CASE : List[str] = output_stride SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion SCREAMING_SNAKE_CASE : Any = finegrained_output SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = scope def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels, pixel_labels def _A ( self : Optional[int] ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Dict = MobileNetVaForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase_ : List[Any] = ( { '''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification, '''image-segmentation''': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Any = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : int = False UpperCamelCase_ : str = False def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def _A ( self : List[Any] ): pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def _A ( self : Dict ): pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def _A ( self : Union[str, Any] ): pass def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): def check_hidden_states_output(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 16 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : str = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def _A ( self : Optional[Any] ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : int = MobileNetVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Optional[int] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ ) # verify the logits SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : int = model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.tensor( [ [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]], [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]], [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available snake_case = { """configuration_ernie""": ["""ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ErnieConfig""", """ErnieOnnxConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST""", """ErnieForCausalLM""", """ErnieForMaskedLM""", """ErnieForMultipleChoice""", """ErnieForNextSentencePrediction""", """ErnieForPreTraining""", """ErnieForQuestionAnswering""", """ErnieForSequenceClassification""", """ErnieForTokenClassification""", """ErnieModel""", """ErniePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" def constraint_to_multiple_of(lowercase , lowercase , lowercase=0 , lowercase=None ): SCREAMING_SNAKE_CASE : Any = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : int = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Tuple = (output_size, output_size) if isinstance(lowercase , lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_image_size(lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Tuple = output_height / input_height SCREAMING_SNAKE_CASE : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width SCREAMING_SNAKE_CASE : List[str] = scale_width else: # fit height SCREAMING_SNAKE_CASE : Optional[Any] = scale_height SCREAMING_SNAKE_CASE : int = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase ) SCREAMING_SNAKE_CASE : Dict = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase ) return (new_height, new_width) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase_ : str , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = size if size is not None else {"height": 384, "width": 384} SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : int = ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample SCREAMING_SNAKE_CASE : List[str] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self : Tuple , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : int , ): SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = get_resize_output_image_size( UpperCAmelCase_ , output_size=(size["height"], size["width"]) , keep_aspect_ratio=UpperCAmelCase_ , multiple=UpperCAmelCase_ , ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Dict , ): return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ): return normalize(UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : Optional[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : List[str] = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Any = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Tuple = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Tuple = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Tuple] = None ): SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : str = [] for idx in range(len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
62
1
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeling_tf_common import floats_tensor from .test_framework_agnostic import GenerationIntegrationTestsMixin if is_tf_available(): import tensorflow as tf from transformers import ( AutoTokenizer, TFAutoModelForCausalLM, TFAutoModelForSeqaSeqLM, TFAutoModelForSpeechSeqaSeq, TFAutoModelForVisionaSeq, TFBartForConditionalGeneration, TFLogitsProcessorList, TFMinLengthLogitsProcessor, tf_top_k_top_p_filtering, ) if is_tensorflow_text_available(): import tensorflow_text as text @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[Any] = tf.convert_to_tensor( [ [ 8.2_220_991, # 3rd highest value; idx. 0 -0.5_620_044, 5.23_229_752, 4.0_386_393, -6.8_798_378, -0.54_785_802, -3.2_012_153, 2.92_777_176, 1.88_171_953, 7.35_341_276, # 5th highest value; idx. 9 8.43_207_833, # 2nd highest value; idx. 10 -9.85_711_836, -5.96_209_236, -1.13_039_161, -7.1_115_294, -0.8_369_633, -5.3_186_408, 7.06_427_407, 0.81_369_344, -0.82_023_817, -5.9_179_796, 0.58_813_443, -6.99_778_438, 4.71_551_189, -0.18_771_637, 7.44_020_759, # 4th highest value; idx. 25 9.38_450_987, # 1st highest value; idx. 26 2.12_662_941, -9.32_562_038, 2.35_652_522, ], # cummulative prob of 5 highest values <= 0.6 [ 0.58_425_518, 4.53_139_238, -5.57_510_464, -6.28_030_699, -7.19_529_503, -4.02_122_551, 1.39_337_037, -6.06_707_057, 1.59_480_517, -9.643_119, 0.03_907_799, 0.67_231_762, -8.88_206_726, 6.27_115_922, # 4th highest value; idx. 13 2.28_520_723, 4.82_767_506, 4.30_421_368, 8.8_275_313, # 2nd highest value; idx. 17 5.44_029_958, # 5th highest value; idx. 18 -4.4_735_794, 7.38_579_536, # 3rd highest value; idx. 20 -2.91_051_663, 2.61_946_077, -2.5_674_762, -9.48_959_302, -4.02_922_645, -1.35_416_918, 9.67_702_323, # 1st highest value; idx. 27 -5.89_478_553, 1.85_370_467, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) SCREAMING_SNAKE_CASE : Tuple = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above SCREAMING_SNAKE_CASE : List[str] = tf.convert_to_tensor( [8.222_099, 7.3_534_126, 8.432_078, 7.4_402_075, 9.38_451, 6.271_159, 8.827_531, 5.4_402_995, 7.3_857_956, 9.677_023] , dtype=tf.floataa , ) # expected non filtered values as noted above SCREAMING_SNAKE_CASE : Optional[Any] = tf_top_k_top_p_filtering(UpperCAmelCase_ , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 ) SCREAMING_SNAKE_CASE : Optional[int] = output[output != -float("inf" )] SCREAMING_SNAKE_CASE : Optional[Any] = tf.cast( tf.where(tf.not_equal(UpperCAmelCase_ , tf.constant(-float("inf" ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(UpperCAmelCase_ , UpperCAmelCase_ , rtol=1E-12 ) tf.debugging.assert_equal(UpperCAmelCase_ , UpperCAmelCase_ ) @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase , lowerCAmelCase ): '''simple docstring''' if is_tf_available(): UpperCamelCase_ : List[str] = { '''AutoModelForCausalLM''': TFAutoModelForCausalLM, '''AutoModelForSpeechSeq2Seq''': TFAutoModelForSpeechSeqaSeq, '''AutoModelForSeq2SeqLM''': TFAutoModelForSeqaSeqLM, '''AutoModelForVision2Seq''': TFAutoModelForVisionaSeq, '''LogitsProcessorList''': TFLogitsProcessorList, '''MinLengthLogitsProcessor''': TFMinLengthLogitsProcessor, '''create_tensor_fn''': tf.convert_to_tensor, '''floats_tensor''': floats_tensor, '''return_tensors''': '''tf''', } @slow def _A ( self : Tuple ): # TF-only test: tf.saved_model export SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : List[Any] = 2 SCREAMING_SNAKE_CASE : Optional[int] = 2 class SCREAMING_SNAKE_CASE ( tf.Module ): '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : Dict ): super(UpperCAmelCase_ , self ).__init__() SCREAMING_SNAKE_CASE : List[Any] = model @tf.function( input_signature=( tf.TensorSpec((None, input_length) , tf.intaa , name="input_ids" ), tf.TensorSpec((None, input_length) , tf.intaa , name="attention_mask" ), ) , jit_compile=UpperCAmelCase_ , ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : Dict = self.model.generate( input_ids=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , max_new_tokens=UpperCAmelCase_ , return_dict_in_generate=UpperCAmelCase_ , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : int = [[2, 0], [102, 103]] SCREAMING_SNAKE_CASE : Tuple = [[1, 0], [1, 1]] SCREAMING_SNAKE_CASE : Optional[Any] = DummyModel(model=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(UpperCAmelCase_ , UpperCAmelCase_ , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.saved_model.load(UpperCAmelCase_ ).signatures["serving_default"] for batch_size in range(1 , len(UpperCAmelCase_ ) + 1 ): SCREAMING_SNAKE_CASE : Tuple = { "input_ids": tf.constant(dummy_input_ids[:batch_size] ), "attention_mask": tf.constant(dummy_attention_masks[:batch_size] ), } SCREAMING_SNAKE_CASE : List[Any] = serving_func(**UpperCAmelCase_ )["sequences"] SCREAMING_SNAKE_CASE : Tuple = test_model.generate(**UpperCAmelCase_ , max_new_tokens=UpperCAmelCase_ ) tf.debugging.assert_equal(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def _A ( self : Tuple ): # TF-only test: tf.saved_model export SCREAMING_SNAKE_CASE : Union[str, Any] = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Dict = 2 class SCREAMING_SNAKE_CASE ( tf.Module ): '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int ): super(UpperCAmelCase_ , self ).__init__() SCREAMING_SNAKE_CASE : List[Any] = model @tf.function( input_signature=( tf.TensorSpec((batch_size, None) , tf.intaa , name="input_ids" ), tf.TensorSpec((batch_size, None) , tf.intaa , name="attention_mask" ), ) , jit_compile=UpperCAmelCase_ , ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : str = self.model.generate( input_ids=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , max_new_tokens=UpperCAmelCase_ , return_dict_in_generate=UpperCAmelCase_ , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : Optional[Any] = [[2], [102, 103]] SCREAMING_SNAKE_CASE : Dict = [[1], [1, 1]] SCREAMING_SNAKE_CASE : str = DummyModel(model=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(UpperCAmelCase_ , UpperCAmelCase_ , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.saved_model.load(UpperCAmelCase_ ).signatures["serving_default"] for input_row in range(len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE : Any = { "input_ids": tf.constant([dummy_input_ids[input_row]] ), "attention_mask": tf.constant([dummy_attention_masks[input_row]] ), } SCREAMING_SNAKE_CASE : List[str] = serving_func(**UpperCAmelCase_ )["sequences"] SCREAMING_SNAKE_CASE : List[str] = test_model.generate(**UpperCAmelCase_ , max_new_tokens=UpperCAmelCase_ ) tf.debugging.assert_equal(UpperCAmelCase_ , UpperCAmelCase_ ) @slow @require_tensorflow_text def _A ( self : Any ): # TF-only test: tf.saved_model export with tempfile.TemporaryDirectory() as tmp_dir: # file needed to load the TF tokenizer hf_hub_download(repo_id="google/flan-t5-small" , filename="spiece.model" , local_dir=UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : int ): super().__init__() SCREAMING_SNAKE_CASE : List[str] = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(UpperCAmelCase_ , "spiece.model" ) , "rb" ).read() ) SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained("hf-internal-testing/tiny-random-t5" ) def _A ( self : int , UpperCAmelCase_ : Tuple , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Dict = self.tokenizer.tokenize(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = text.pad_model_inputs( UpperCAmelCase_ , max_seq_length=64 , pad_value=self.model.config.pad_token_id ) SCREAMING_SNAKE_CASE : str = self.model.generate(input_ids=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) return self.tokenizer.detokenize(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = CompleteSentenceTransformer() SCREAMING_SNAKE_CASE : List[str] = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name="inputs" ) SCREAMING_SNAKE_CASE : List[Any] = complete_model(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.keras.Model(UpperCAmelCase_ , UpperCAmelCase_ ) keras_model.save(UpperCAmelCase_ ) def _A ( self : Any ): # Has PT equivalent: this test relies on random sampling SCREAMING_SNAKE_CASE : List[str] = { "do_sample": True, "num_beams": 1, "top_p": 0.7, "top_k": 10, "temperature": 0.7, } SCREAMING_SNAKE_CASE : Union[str, Any] = 14 SCREAMING_SNAKE_CASE : str = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : str = "Hello, my dog is cute and" SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(UpperCAmelCase_ , return_tensors="tf" ) SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : Any = 638 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = model.generate(**UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) self.assertTrue(expectation == len(generated_tokens[0] ) ) SCREAMING_SNAKE_CASE : Dict = [638, 198] with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = model.generate(**UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def _A ( self : Tuple ): # Has PT equivalent: ample use of framework-specific code SCREAMING_SNAKE_CASE : Dict = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : str = "Hugging Face is a technology company based in New York and Paris." SCREAMING_SNAKE_CASE : Union[str, Any] = bart_tokenizer(UpperCAmelCase_ , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : Tuple = TFBartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : List[str] = bart_model.generate(UpperCAmelCase_ ).numpy() class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : Optional[Any] ): return super().call(UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = FakeBart.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : Any = bart_model.generate(UpperCAmelCase_ , foo="bar" ).numpy() self.assertTrue(np.array_equal(UpperCAmelCase_ , UpperCAmelCase_ ) ) class SCREAMING_SNAKE_CASE ( bart_model.model.encoder.__class__ ): '''simple docstring''' def _A ( self : str , UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ): return super().call(UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = FakeEncoder(bart_model.config , bart_model.model.shared ) SCREAMING_SNAKE_CASE : Any = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) SCREAMING_SNAKE_CASE : Any = bart_model.generate(UpperCAmelCase_ ).numpy() with self.assertRaises(UpperCAmelCase_ ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(UpperCAmelCase_ , foo="bar" )
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : int = 6 ): SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None self.create_linked_list(UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Optional[int] = Node() SCREAMING_SNAKE_CASE : str = current_node SCREAMING_SNAKE_CASE : Optional[int] = current_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node for _ in range(1 , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Tuple = Node() SCREAMING_SNAKE_CASE : Dict = current_node SCREAMING_SNAKE_CASE : Optional[Any] = previous_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node SCREAMING_SNAKE_CASE : Union[str, Any] = self.front SCREAMING_SNAKE_CASE : List[str] = previous_node def _A ( self : Union[str, Any] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _A ( self : Optional[int] ): self.check_can_perform_operation() return self.front.data if self.front else None def _A ( self : Optional[int] , UpperCAmelCase_ : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE : List[str] = self.rear.next if self.rear: SCREAMING_SNAKE_CASE : Dict = data def _A ( self : List[str] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE : List[str] = self.front.data SCREAMING_SNAKE_CASE : Optional[int] = None return data SCREAMING_SNAKE_CASE : List[str] = self.front SCREAMING_SNAKE_CASE : List[str] = old_front.next SCREAMING_SNAKE_CASE : Optional[int] = old_front.data SCREAMING_SNAKE_CASE : List[str] = None return data def _A ( self : Any ): if self.is_empty(): raise Exception("Empty Queue" ) def _A ( self : Optional[Any] ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any | None = None SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
62
1
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Dict = FunnelTokenizer UpperCamelCase_ : Dict = FunnelTokenizerFast UpperCamelCase_ : Union[str, Any] = True UpperCamelCase_ : int = True def _A ( self : int ): super().setUp() SCREAMING_SNAKE_CASE : Dict = [ "<unk>", "<cls>", "<sep>", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : Union[str, Any] , **UpperCAmelCase_ : int ): return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : int , **UpperCAmelCase_ : Union[str, Any] ): return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : str , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Tuple = "UNwant\u00E9d,running" SCREAMING_SNAKE_CASE : Union[str, Any] = "unwanted, running" return input_text, output_text def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [7, 4, 5, 10, 8, 9] ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : str = self.get_tokenizers(do_lower_case=UpperCAmelCase_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE : List[Any] = tokenizer("UNwant\u00E9d,running" ) SCREAMING_SNAKE_CASE : Optional[Any] = len(inputs["input_ids"] ) - 1 self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer("UNwant\u00E9d,running" , "UNwant\u00E9d,running" ) self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len + [1] * sentence_len )
62
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
62
1
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict=13 , UpperCAmelCase_ : Dict=30 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Optional[Any]=37 , UpperCAmelCase_ : Dict="gelu" , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Dict=10 , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : str=3 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]=2 , ): SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : List[str] = batch_size SCREAMING_SNAKE_CASE : Optional[int] = image_size SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : List[Any] = num_channels SCREAMING_SNAKE_CASE : Union[str, Any] = is_training SCREAMING_SNAKE_CASE : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Dict = num_hidden_layers SCREAMING_SNAKE_CASE : Any = num_attention_heads SCREAMING_SNAKE_CASE : int = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : int = type_sequence_label_size SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = scope SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE : List[Any] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE : List[Any] = num_patches + 2 def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : int = self.get_config() return config, pixel_values, labels def _A ( self : Optional[Any] ): return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _A ( self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : int = DeiTModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : Tuple = DeiTForMaskedImageModeling(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : int = model(UpperCAmelCase_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : str = DeiTForMaskedImageModeling(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : List[str] = model(UpperCAmelCase_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _A ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : str = self.type_sequence_label_size SCREAMING_SNAKE_CASE : Dict = DeiTForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : int = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : int = DeiTForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Tuple = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Tuple = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : str = config_and_inputs SCREAMING_SNAKE_CASE : str = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) UpperCamelCase_ : Optional[int] = ( { '''feature-extraction''': DeiTModel, '''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) UpperCamelCase_ : str = False UpperCamelCase_ : List[Any] = False UpperCamelCase_ : Any = False def _A ( self : Any ): SCREAMING_SNAKE_CASE : Union[str, Any] = DeiTModelTester(self ) SCREAMING_SNAKE_CASE : List[Any] = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def _A ( self : Tuple ): pass def _A ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase_ , nn.Linear ) ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[Any] = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : str = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : str ): SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict=False ): SCREAMING_SNAKE_CASE : str = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _A ( self : Optional[Any] ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(UpperCAmelCase_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE : int = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() SCREAMING_SNAKE_CASE : List[Any] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = model(**UpperCAmelCase_ ).loss loss.backward() def _A ( self : str ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE : Optional[int] = False SCREAMING_SNAKE_CASE : int = True for model_class in self.all_model_classes: if model_class in get_values(UpperCAmelCase_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE : Optional[int] = model_class(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.to(UpperCAmelCase_ ) model.train() SCREAMING_SNAKE_CASE : Tuple = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = model(**UpperCAmelCase_ ).loss loss.backward() def _A ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : int = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE : str = problem_type["title"] SCREAMING_SNAKE_CASE : Optional[int] = problem_type["num_labels"] SCREAMING_SNAKE_CASE : str = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE : Optional[Any] = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) SCREAMING_SNAKE_CASE : Optional[Any] = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=UpperCAmelCase_ ) as warning_list: SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def _A ( self : int ): for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : List[str] = DeiTModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Tuple ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE : Dict = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ ) # verify the logits SCREAMING_SNAKE_CASE : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = torch.tensor([-1.0_266, 0.1_912, -1.2_861] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[Any] = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor SCREAMING_SNAKE_CASE : str = prepare_img() SCREAMING_SNAKE_CASE : int = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ) SCREAMING_SNAKE_CASE : Any = inputs.pixel_values.to(UpperCAmelCase_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ )
62
import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ ( lowercase , lowercase , lowercase = 1 , lowercase = 1 , lowercase = 1.0E4 , lowercase = False , lowercase = 1.0 , ): """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even''' SCREAMING_SNAKE_CASE : Union[str, Any] = float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE : Optional[Any] = min_timescale * jnp.exp(jnp.arange(lowercase , dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE : Optional[int] = jnp.expand_dims(lowercase , 1 ) * jnp.expand_dims(lowercase , 0 ) # scale embeddings SCREAMING_SNAKE_CASE : Optional[int] = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate([jnp.cos(lowercase ), jnp.sin(lowercase )] , axis=1 ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.concatenate([jnp.sin(lowercase ), jnp.cos(lowercase )] , axis=1 ) SCREAMING_SNAKE_CASE : Tuple = jnp.reshape(lowercase , [jnp.shape(lowercase )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.silu(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(UpperCAmelCase_ ) return temb class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : bool = False UpperCamelCase_ : float = 1 @nn.compact def __call__( self : Optional[int] , UpperCAmelCase_ : int ): return get_sinusoidal_embeddings( UpperCAmelCase_ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
62
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""", # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = '''altclip_text_model''' def __init__( self : Optional[int] , UpperCAmelCase_ : List[Any]=25_0002 , UpperCAmelCase_ : Any=1024 , UpperCAmelCase_ : Optional[int]=24 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : Dict=4096 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : int=514 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : List[str]=0.02 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : Tuple=1E-05 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[str]=0 , UpperCAmelCase_ : Optional[int]=2 , UpperCAmelCase_ : int="absolute" , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Tuple=768 , **UpperCAmelCase_ : Any , ): super().__init__(pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Dict = num_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : Tuple = initializer_factor SCREAMING_SNAKE_CASE : Any = layer_norm_eps SCREAMING_SNAKE_CASE : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE : Union[str, Any] = use_cache SCREAMING_SNAKE_CASE : int = project_dim class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''altclip_vision_model''' def __init__( self : str , UpperCAmelCase_ : Union[str, Any]=768 , UpperCAmelCase_ : List[Any]=3072 , UpperCAmelCase_ : List[Any]=512 , UpperCAmelCase_ : Dict=12 , UpperCAmelCase_ : Union[str, Any]=12 , UpperCAmelCase_ : Optional[int]=3 , UpperCAmelCase_ : Optional[Any]=224 , UpperCAmelCase_ : Optional[int]=32 , UpperCAmelCase_ : Any="quick_gelu" , UpperCAmelCase_ : Optional[int]=1E-5 , UpperCAmelCase_ : Tuple=0.0 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Any=1.0 , **UpperCAmelCase_ : Any , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : Tuple = projection_dim SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Any = num_channels SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : Any = initializer_factor SCREAMING_SNAKE_CASE : Any = attention_dropout SCREAMING_SNAKE_CASE : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[int] = hidden_act @classmethod def _A ( cls : Any , UpperCAmelCase_ : Union[str, os.PathLike] , **UpperCAmelCase_ : str ): cls._set_token_in_kwargs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = cls.get_config_dict(UpperCAmelCase_ , **UpperCAmelCase_ ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get("model_type" ) == "altclip": SCREAMING_SNAKE_CASE : Union[str, Any] = 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 SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = '''altclip''' UpperCamelCase_ : List[Any] = True def __init__( self : str , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Any=768 , UpperCAmelCase_ : str=2.6_592 , **UpperCAmelCase_ : Optional[Any] ): # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop("text_config_dict" , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.pop("vision_config_dict" , UpperCAmelCase_ ) super().__init__(**UpperCAmelCase_ ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: SCREAMING_SNAKE_CASE : Optional[Any] = {} # This is the complete result when using `text_config_dict`. SCREAMING_SNAKE_CASE : Union[str, Any] = AltCLIPTextConfig(**UpperCAmelCase_ ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: SCREAMING_SNAKE_CASE : int = ( f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. ''' f'''The value `text_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: SCREAMING_SNAKE_CASE : Any = ( f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ''' f'''value `text_config["{key}"]` will be overriden.''' ) logger.warning(UpperCAmelCase_ ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: SCREAMING_SNAKE_CASE : Dict = {} # This is the complete result when using `vision_config_dict`. SCREAMING_SNAKE_CASE : Any = AltCLIPVisionConfig(**UpperCAmelCase_ ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: SCREAMING_SNAKE_CASE : List[str] = { str(UpperCAmelCase_ ): value for key, value in _vision_config_dict["id2label"].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: SCREAMING_SNAKE_CASE : Union[str, Any] = ( f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different ''' f'''values. The value `vision_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: SCREAMING_SNAKE_CASE : Tuple = ( f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ''' f'''The value `vision_config["{key}"]` will be overriden.''' ) logger.warning(UpperCAmelCase_ ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: SCREAMING_SNAKE_CASE : Tuple = {} logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values." ) if vision_config is None: SCREAMING_SNAKE_CASE : Dict = {} logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values." ) SCREAMING_SNAKE_CASE : Optional[int] = AltCLIPTextConfig(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = AltCLIPVisionConfig(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = projection_dim SCREAMING_SNAKE_CASE : Union[str, Any] = logit_scale_init_value SCREAMING_SNAKE_CASE : Optional[Any] = 1.0 @classmethod def _A ( cls : Union[str, Any] , UpperCAmelCase_ : AltCLIPTextConfig , UpperCAmelCase_ : AltCLIPVisionConfig , **UpperCAmelCase_ : int ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : int = self.text_config.to_dict() SCREAMING_SNAKE_CASE : Optional[int] = self.vision_config.to_dict() SCREAMING_SNAKE_CASE : Dict = self.__class__.model_type return output
62
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ : Any = '''image_segmenter''' UpperCamelCase_ : int = CLIPSegForImageSegmentation UpperCamelCase_ : Optional[Any] = ['''image''', '''text'''] UpperCamelCase_ : int = ['''image'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): with torch.no_grad(): SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits return logits def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
62
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING snake_case = logging.get_logger(__name__) snake_case = { """ut/deta""": """https://huggingface.co/ut/deta/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = '''deta''' UpperCamelCase_ : Dict = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : List[str]=900 , UpperCAmelCase_ : Optional[int]=2048 , UpperCAmelCase_ : Tuple=6 , UpperCAmelCase_ : str=2048 , UpperCAmelCase_ : Optional[Any]=8 , UpperCAmelCase_ : Union[str, Any]=6 , UpperCAmelCase_ : List[str]=1024 , UpperCAmelCase_ : int=8 , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Dict="relu" , UpperCAmelCase_ : Tuple=256 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : str=0.0 , UpperCAmelCase_ : Tuple=0.0 , UpperCAmelCase_ : Tuple=0.02 , UpperCAmelCase_ : List[Any]=1.0 , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : Tuple="sine" , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Optional[int]=300 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Optional[Any]=5 , UpperCAmelCase_ : Optional[Any]=2 , UpperCAmelCase_ : List[Any]=1 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[Any]=0.25 , **UpperCAmelCase_ : Tuple , ): if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) SCREAMING_SNAKE_CASE : Union[str, Any] = CONFIG_MAPPING["resnet"](out_features=["stage2", "stage3", "stage4"] ) else: if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Tuple = backbone_config.pop("model_type" ) SCREAMING_SNAKE_CASE : Tuple = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE : Dict = config_class.from_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = backbone_config SCREAMING_SNAKE_CASE : Tuple = num_queries SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = d_model SCREAMING_SNAKE_CASE : str = encoder_ffn_dim SCREAMING_SNAKE_CASE : Dict = encoder_layers SCREAMING_SNAKE_CASE : Dict = encoder_attention_heads SCREAMING_SNAKE_CASE : Any = decoder_ffn_dim SCREAMING_SNAKE_CASE : Any = decoder_layers SCREAMING_SNAKE_CASE : List[Any] = decoder_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = dropout SCREAMING_SNAKE_CASE : str = attention_dropout SCREAMING_SNAKE_CASE : List[str] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = activation_function SCREAMING_SNAKE_CASE : List[Any] = init_std SCREAMING_SNAKE_CASE : Any = init_xavier_std SCREAMING_SNAKE_CASE : Optional[Any] = encoder_layerdrop SCREAMING_SNAKE_CASE : List[Any] = auxiliary_loss SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type # deformable attributes SCREAMING_SNAKE_CASE : int = num_feature_levels SCREAMING_SNAKE_CASE : List[str] = encoder_n_points SCREAMING_SNAKE_CASE : str = decoder_n_points SCREAMING_SNAKE_CASE : List[str] = two_stage SCREAMING_SNAKE_CASE : int = two_stage_num_proposals SCREAMING_SNAKE_CASE : int = with_box_refine SCREAMING_SNAKE_CASE : Dict = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("If two_stage is True, with_box_refine must be True." ) # Hungarian matcher SCREAMING_SNAKE_CASE : Tuple = class_cost SCREAMING_SNAKE_CASE : Optional[Any] = bbox_cost SCREAMING_SNAKE_CASE : Any = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE : List[Any] = mask_loss_coefficient SCREAMING_SNAKE_CASE : Tuple = dice_loss_coefficient SCREAMING_SNAKE_CASE : Dict = bbox_loss_coefficient SCREAMING_SNAKE_CASE : List[Any] = giou_loss_coefficient SCREAMING_SNAKE_CASE : int = eos_coefficient SCREAMING_SNAKE_CASE : str = focal_alpha super().__init__(is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_ ) @property def _A ( self : Dict ): return self.encoder_attention_heads @property def _A ( self : int ): return self.d_model def _A ( self : str ): SCREAMING_SNAKE_CASE : List[str] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE : Any = self.__class__.model_type return output
62
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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BlenderbotSmallTokenizer UpperCamelCase_ : int = False def _A ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] SCREAMING_SNAKE_CASE : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : List[Any] , **UpperCAmelCase_ : str ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : int = "adapt act apte" return input_text, output_text def _A ( self : str ): SCREAMING_SNAKE_CASE : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : List[str] = ["adapt", "act", "ap@@", "te"] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1384] SCREAMING_SNAKE_CASE : str = "I am a small frog." SCREAMING_SNAKE_CASE : List[Any] = tok([src_text] , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : int = tok.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) SCREAMING_SNAKE_CASE : Tuple = "I am a small frog ." SCREAMING_SNAKE_CASE : Optional[int] = "." SCREAMING_SNAKE_CASE : Dict = tok(UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : Optional[Any] = tok(UpperCAmelCase_ )["input_ids"] assert encoded[-1] == encoded_dot[0]
62
1
import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging snake_case = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = "https://pypi.org/pypi/diffusers/json" SCREAMING_SNAKE_CASE : List[str] = json.loads(request.urlopen(lowercase ).read() )["releases"].keys() return sorted(lowercase , key=lambda lowercase : version.Version(lowercase ) ) def lowerCamelCase__ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) SCREAMING_SNAKE_CASE : List[str] = Path(lowercase ) / "__init__.py" if not init_path.exists(): init_path.touch() def lowerCamelCase__ ( lowercase ): """simple docstring""" init_hf_modules() SCREAMING_SNAKE_CASE : Optional[Any] = Path(lowercase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(lowercase , exist_ok=lowercase ) SCREAMING_SNAKE_CASE : Any = dynamic_module_path / "__init__.py" if not init_path.exists(): init_path.touch() def lowerCamelCase__ ( lowercase ): """simple docstring""" with open(lowercase , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE : Dict = f.read() # Imports of the form `import .xxx` SCREAMING_SNAKE_CASE : int = re.findall("^\s*import\s+\.(\S+)\s*$" , lowercase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import" , lowercase , flags=re.MULTILINE ) # Unique-ify return list(set(lowercase ) ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : List[str] = [module_file] SCREAMING_SNAKE_CASE : Dict = [] # Let's recurse through all relative imports while not no_change: SCREAMING_SNAKE_CASE : Optional[Any] = [] for f in files_to_check: new_imports.extend(get_relative_imports(lowercase ) ) SCREAMING_SNAKE_CASE : str = Path(lowercase ).parent SCREAMING_SNAKE_CASE : int = [str(module_path / m ) for m in new_imports] SCREAMING_SNAKE_CASE : List[str] = [f for f in new_import_files if f not in all_relative_imports] SCREAMING_SNAKE_CASE : Dict = [F'''{f}.py''' for f in new_import_files] SCREAMING_SNAKE_CASE : Optional[Any] = len(lowercase ) == 0 all_relative_imports.extend(lowercase ) return all_relative_imports def lowerCamelCase__ ( lowercase ): """simple docstring""" with open(lowercase , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE : Optional[Any] = f.read() # Imports of the form `import xxx` SCREAMING_SNAKE_CASE : int = re.findall("^\s*import\s+(\S+)\s*$" , lowercase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall("^\s*from\s+(\S+)\s+import" , lowercase , flags=re.MULTILINE ) # Only keep the top-level module SCREAMING_SNAKE_CASE : List[Any] = [imp.split("." )[0] for imp in imports if not imp.startswith("." )] # Unique-ify and test we got them all SCREAMING_SNAKE_CASE : Tuple = list(set(lowercase ) ) SCREAMING_SNAKE_CASE : Any = [] for imp in imports: try: importlib.import_module(lowercase ) except ImportError: missing_packages.append(lowercase ) if len(lowercase ) > 0: raise ImportError( "This modeling file requires the following packages that were not found in your environment: " F'''{', '.join(lowercase )}. Run `pip install {' '.join(lowercase )}`''' ) return get_relative_imports(lowercase ) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = module_path.replace(os.path.sep , "." ) SCREAMING_SNAKE_CASE : Optional[Any] = importlib.import_module(lowercase ) if class_name is None: return find_pipeline_class(lowercase ) return getattr(lowercase , lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" from ..pipelines import DiffusionPipeline SCREAMING_SNAKE_CASE : Union[str, Any] = dict(inspect.getmembers(lowercase , inspect.isclass ) ) SCREAMING_SNAKE_CASE : Tuple = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , lowercase ) and cls.__module__.split("." )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) SCREAMING_SNAKE_CASE : Optional[int] = cls return pipeline_class def lowerCamelCase__ ( lowercase , lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase ) SCREAMING_SNAKE_CASE : Dict = os.path.join(lowercase , lowercase ) if os.path.isfile(lowercase ): SCREAMING_SNAKE_CASE : Any = module_file_or_url SCREAMING_SNAKE_CASE : Any = "local" elif pretrained_model_name_or_path.count("/" ) == 0: SCREAMING_SNAKE_CASE : int = get_diffusers_versions() # cut ".dev0" SCREAMING_SNAKE_CASE : int = "v" + ".".join(__version__.split("." )[:3] ) # retrieve github version that matches if revision is None: SCREAMING_SNAKE_CASE : str = latest_version if latest_version[1:] in available_versions else "main" logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: SCREAMING_SNAKE_CASE : Tuple = F'''v{revision}''' elif revision == "main": SCREAMING_SNAKE_CASE : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub SCREAMING_SNAKE_CASE : Optional[Any] = COMMUNITY_PIPELINES_URL.format(revision=lowercase , pipeline=lowercase ) try: SCREAMING_SNAKE_CASE : Optional[int] = cached_download( lowercase , cache_dir=lowercase , force_download=lowercase , proxies=lowercase , resume_download=lowercase , local_files_only=lowercase , use_auth_token=lowercase , ) SCREAMING_SNAKE_CASE : str = "git" SCREAMING_SNAKE_CASE : Optional[Any] = pretrained_model_name_or_path + ".py" except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached SCREAMING_SNAKE_CASE : Optional[Any] = hf_hub_download( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , proxies=lowercase , resume_download=lowercase , local_files_only=lowercase , use_auth_token=lowercase , ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join("local" , "--".join(pretrained_model_name_or_path.split("/" ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment SCREAMING_SNAKE_CASE : Optional[int] = check_imports(lowercase ) # Now we move the module inside our cached dynamic modules. SCREAMING_SNAKE_CASE : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(lowercase ) SCREAMING_SNAKE_CASE : Any = Path(lowercase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(lowercase , submodule_path / module_file ) for module_needed in modules_needed: SCREAMING_SNAKE_CASE : Dict = F'''{module_needed}.py''' shutil.copy(os.path.join(lowercase , lowercase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = use_auth_token elif use_auth_token is True: SCREAMING_SNAKE_CASE : List[Any] = HfFolder.get_token() else: SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Any = model_info(lowercase , revision=lowercase , token=lowercase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. SCREAMING_SNAKE_CASE : str = submodule_path / commit_hash SCREAMING_SNAKE_CASE : Union[str, Any] = full_submodule + os.path.sep + commit_hash create_dynamic_module(lowercase ) if not (submodule_path / module_file).exists(): shutil.copy(lowercase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( lowercase , F'''{module_needed}.py''' , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) return os.path.join(lowercase , lowercase ) def lowerCamelCase__ ( lowercase , lowercase , lowercase = None , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = get_cached_module_file( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) return get_class_in_module(lowercase , final_module.replace(".py" , "" ) )
62
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] snake_case = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = torch.load(lowercase , map_location="cpu" ) return sd def lowerCamelCase__ ( lowercase , lowercase , lowercase=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE : Union[str, Any] = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE : Any = new_key.replace(name_pair[0] , name_pair[1] ) SCREAMING_SNAKE_CASE : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE : Union[str, Any] = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = "pretraining" if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Any = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 512} SCREAMING_SNAKE_CASE : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = {"visual_embedding_dim": 2048} SCREAMING_SNAKE_CASE : str = "vqa_advanced" elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Tuple = {"visual_embedding_dim": 2048, "num_labels": 3129} SCREAMING_SNAKE_CASE : Optional[Any] = "vqa" elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = { "visual_embedding_dim": 1024, "num_labels": 2, } SCREAMING_SNAKE_CASE : Tuple = "nlvr" SCREAMING_SNAKE_CASE : List[Any] = VisualBertConfig(**lowercase ) # Load State Dict SCREAMING_SNAKE_CASE : List[str] = load_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Any = get_new_dict(lowercase , lowercase ) if model_type == "pretraining": SCREAMING_SNAKE_CASE : int = VisualBertForPreTraining(lowercase ) elif model_type == "vqa": SCREAMING_SNAKE_CASE : Tuple = VisualBertForQuestionAnswering(lowercase ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE : List[Any] = VisualBertForVisualReasoning(lowercase ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE : Optional[Any] = VisualBertForMultipleChoice(lowercase ) model.load_state_dict(lowercase ) # Save Checkpoints Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
62
1
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Dict=10 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : int=32 * 4 , UpperCAmelCase_ : str=32 * 6 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Tuple=32 , ): SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : List[Any] = is_training SCREAMING_SNAKE_CASE : Union[str, Any] = use_auxiliary_loss SCREAMING_SNAKE_CASE : Tuple = num_queries SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : Any = min_size SCREAMING_SNAKE_CASE : Union[str, Any] = max_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE : Tuple = mask_feature_size def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch.ones([self.batch_size, self.min_size, self.max_size] , device=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=UpperCAmelCase_ ) > 0.5 ).float() SCREAMING_SNAKE_CASE : Optional[Any] = (torch.rand((self.batch_size, self.num_labels) , device=UpperCAmelCase_ ) > 0.5).long() SCREAMING_SNAKE_CASE : List[str] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _A ( self : Any ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def _A ( self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = output.encoder_hidden_states SCREAMING_SNAKE_CASE : List[Any] = output.pixel_decoder_hidden_states SCREAMING_SNAKE_CASE : str = output.transformer_decoder_hidden_states self.parent.assertTrue(len(UpperCAmelCase_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(UpperCAmelCase_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(UpperCAmelCase_ ) , config.decoder_config.decoder_layers ) def _A ( self : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str]=False ): with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[int] = MaskFormerModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=UpperCAmelCase_ , pixel_mask=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = model(UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Optional[int] = MaskFormerForInstanceSegmentation(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() def comm_check_on_output(UpperCAmelCase_ : int ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(pixel_values=UpperCAmelCase_ , pixel_mask=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(UpperCAmelCase_ ) comm_check_on_output(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = model( pixel_values=UpperCAmelCase_ , pixel_mask=UpperCAmelCase_ , mask_labels=UpperCAmelCase_ , class_labels=UpperCAmelCase_ ) comm_check_on_output(UpperCAmelCase_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () UpperCamelCase_ : List[str] = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) UpperCamelCase_ : int = False UpperCamelCase_ : Union[str, Any] = False UpperCamelCase_ : int = False UpperCamelCase_ : Optional[Any] = False def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Any = MaskFormerModelTester(self ) SCREAMING_SNAKE_CASE : Tuple = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _A ( self : List[str] ): self.config_tester.run_common_tests() def _A ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(UpperCAmelCase_ , **UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*UpperCAmelCase_ ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def _A ( self : List[str] ): pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def _A ( self : Optional[int] ): pass @unittest.skip(reason="MaskFormer is not a generative model" ) def _A ( self : List[str] ): pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def _A ( self : Union[str, Any] ): pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def _A ( self : List[Any] ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _A ( self : Tuple ): pass def _A ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : List[str] = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Optional[int] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) @slow def _A ( self : List[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: SCREAMING_SNAKE_CASE : Any = MaskFormerModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = (self.model_tester.min_size,) * 2 SCREAMING_SNAKE_CASE : Any = { "pixel_values": torch.randn((2, 3, *size) , device=UpperCAmelCase_ ), "mask_labels": torch.randn((2, 10, *size) , device=UpperCAmelCase_ ), "class_labels": torch.zeros(2 , 10 , device=UpperCAmelCase_ ).long(), } SCREAMING_SNAKE_CASE : Tuple = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = model(**UpperCAmelCase_ ) self.assertTrue(outputs.loss is not None ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(UpperCAmelCase_ , **UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : List[Any] = model_class(UpperCAmelCase_ ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = model(**UpperCAmelCase_ , output_attentions=UpperCAmelCase_ ) self.assertTrue(outputs.attentions is not None ) def _A ( self : Tuple ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss SCREAMING_SNAKE_CASE : str = self.all_model_classes[1] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Dict = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() SCREAMING_SNAKE_CASE : Dict = model(UpperCAmelCase_ , mask_labels=UpperCAmelCase_ , class_labels=UpperCAmelCase_ ).loss loss.backward() def _A ( self : Optional[Any] ): # only MaskFormerForInstanceSegmentation has the loss SCREAMING_SNAKE_CASE : str = self.all_model_classes[1] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : List[Any] = True SCREAMING_SNAKE_CASE : Dict = True SCREAMING_SNAKE_CASE : Optional[int] = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() SCREAMING_SNAKE_CASE : Tuple = model(UpperCAmelCase_ , mask_labels=UpperCAmelCase_ , class_labels=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't SCREAMING_SNAKE_CASE : List[Any] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() SCREAMING_SNAKE_CASE : List[Any] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=UpperCAmelCase_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) snake_case = 1e-4 def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Tuple ): return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[Any] = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE : Any = image_processor(UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(UpperCAmelCase_ , (1, 3, 800, 1088) ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[int] = model(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(UpperCAmelCase_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , UpperCAmelCase_ , atol=UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : int = torch.tensor( [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(UpperCAmelCase_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , UpperCAmelCase_ , atol=UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(UpperCAmelCase_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , UpperCAmelCase_ , atol=UpperCAmelCase_ ) ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(UpperCAmelCase_ ) .eval() ) SCREAMING_SNAKE_CASE : Dict = self.default_image_processor SCREAMING_SNAKE_CASE : List[str] = prepare_img() SCREAMING_SNAKE_CASE : List[str] = image_processor(UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(UpperCAmelCase_ , (1, 3, 800, 1088) ) with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(**UpperCAmelCase_ ) # masks_queries_logits SCREAMING_SNAKE_CASE : Optional[Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) SCREAMING_SNAKE_CASE : Optional[int] = [ [-1.3_737_124, -1.7_724_937, -1.9_364_233], [-1.5_977_281, -1.9_867_939, -2.1_523_695], [-1.5_795_398, -1.9_269_832, -2.093_942], ] SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(UpperCAmelCase_ ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , UpperCAmelCase_ , atol=UpperCAmelCase_ ) ) # class_queries_logits SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [ [1.6_512E00, -5.2_572E00, -3.3_519E00], [3.6_169E-02, -5.9_025E00, -2.9_313E00], [1.0_766E-04, -7.7_630E00, -5.1_263E00], ] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCAmelCase_ , atol=UpperCAmelCase_ ) ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[Any] = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(UpperCAmelCase_ ) .eval() ) SCREAMING_SNAKE_CASE : int = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Any = image_processor(UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(UpperCAmelCase_ , (1, 3, 800, 1088) ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Dict = model(**UpperCAmelCase_ ) # masks_queries_logits SCREAMING_SNAKE_CASE : int = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) SCREAMING_SNAKE_CASE : Dict = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]] SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(UpperCAmelCase_ ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , UpperCAmelCase_ , atol=UpperCAmelCase_ ) ) # class_queries_logits SCREAMING_SNAKE_CASE : str = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) SCREAMING_SNAKE_CASE : Dict = torch.tensor( [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCAmelCase_ , atol=UpperCAmelCase_ ) ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(UpperCAmelCase_ ) .eval() ) SCREAMING_SNAKE_CASE : Dict = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[Any] = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) SCREAMING_SNAKE_CASE : Dict = inputs["pixel_values"].to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = [el.to(UpperCAmelCase_ ) for el in inputs["mask_labels"]] SCREAMING_SNAKE_CASE : Optional[int] = [el.to(UpperCAmelCase_ ) for el in inputs["class_labels"]] with torch.no_grad(): SCREAMING_SNAKE_CASE : Any = model(**UpperCAmelCase_ ) self.assertTrue(outputs.loss is not None )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """JukeboxPriorConfig""", """JukeboxVQVAEConfig""", ], """tokenization_jukebox""": ["""JukeboxTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """JukeboxModel""", """JukeboxPreTrainedModel""", """JukeboxVQVAE""", """JukeboxPrior""", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
1
import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger snake_case = get_logger(__name__) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : List[str] = ( os.path.join(UpperCAmelCase_ , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) SCREAMING_SNAKE_CASE : int = Extractor def _A ( self : Optional[Any] , UpperCAmelCase_ : str ): from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" SCREAMING_SNAKE_CASE : List[Any] = os.path.abspath(UpperCAmelCase_ ) return os.path.join(self.extract_dir , hash_url_to_filename(UpperCAmelCase_ ) ) def _A ( self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool ): return force_extract or ( not os.path.isfile(UpperCAmelCase_ ) and not (os.path.isdir(UpperCAmelCase_ ) and os.listdir(UpperCAmelCase_ )) ) def _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool = False ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.extractor.infer_extractor_format(UpperCAmelCase_ ) if not extractor_format: return input_path SCREAMING_SNAKE_CASE : Optional[Any] = self._get_output_path(UpperCAmelCase_ ) if self._do_extract(UpperCAmelCase_ , UpperCAmelCase_ ): self.extractor.extract(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return output_path class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' @classmethod @abstractmethod def _A ( cls : Any , UpperCAmelCase_ : Union[Path, str] , **UpperCAmelCase_ : str ): ... @staticmethod @abstractmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): ... class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[bytes] = [] @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : int ): with open(UpperCAmelCase_ , "rb" ) as f: return f.read(UpperCAmelCase_ ) @classmethod def _A ( cls : str , UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : bytes = b"" ): if not magic_number: SCREAMING_SNAKE_CASE : List[str] = max(len(UpperCAmelCase_ ) for cls_magic_number in cls.magic_numbers ) try: SCREAMING_SNAKE_CASE : int = cls.read_magic_number(UpperCAmelCase_ , UpperCAmelCase_ ) except OSError: return False return any(magic_number.startswith(UpperCAmelCase_ ) for cls_magic_number in cls.magic_numbers ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' @classmethod def _A ( cls : Dict , UpperCAmelCase_ : Union[Path, str] , **UpperCAmelCase_ : Any ): return tarfile.is_tarfile(UpperCAmelCase_ ) @staticmethod def _A ( UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple ): def resolved(UpperCAmelCase_ : str ) -> str: return os.path.realpath(os.path.abspath(UpperCAmelCase_ ) ) def badpath(UpperCAmelCase_ : str , UpperCAmelCase_ : str ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) ).startswith(UpperCAmelCase_ ) def badlink(UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ) -> bool: # Links are interpreted relative to the directory containing the link SCREAMING_SNAKE_CASE : Union[str, Any] = resolved(os.path.join(UpperCAmelCase_ , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = resolved(UpperCAmelCase_ ) for finfo in members: if badpath(finfo.name , UpperCAmelCase_ ): logger.error(f'''Extraction of {finfo.name} is blocked (illegal path)''' ) elif finfo.issym() and badlink(UpperCAmelCase_ , UpperCAmelCase_ ): logger.error(f'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}''' ) elif finfo.islnk() and badlink(UpperCAmelCase_ , UpperCAmelCase_ ): logger.error(f'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}''' ) else: yield finfo @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = tarfile.open(UpperCAmelCase_ ) tar_file.extractall(UpperCAmelCase_ , members=TarExtractor.safemembers(UpperCAmelCase_ , UpperCAmelCase_ ) ) tar_file.close() class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = [b'''\x1F\x8B'''] @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): with gzip.open(UpperCAmelCase_ , "rb" ) as gzip_file: with open(UpperCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(UpperCAmelCase_ , UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = [ b'''PK\x03\x04''', b'''PK\x05\x06''', # empty archive b'''PK\x07\x08''', # spanned archive ] @classmethod def _A ( cls : Dict , UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : bytes = b"" ): if super().is_extractable(UpperCAmelCase_ , magic_number=UpperCAmelCase_ ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(UpperCAmelCase_ , "rb" ) as fp: SCREAMING_SNAKE_CASE : int = _EndRecData(UpperCAmelCase_ ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: SCREAMING_SNAKE_CASE : Optional[int] = fp.read(UpperCAmelCase_ ) # CD is where we expect it to be if len(UpperCAmelCase_ ) == sizeCentralDir: SCREAMING_SNAKE_CASE : Optional[int] = struct.unpack(UpperCAmelCase_ , UpperCAmelCase_ ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) with zipfile.ZipFile(UpperCAmelCase_ , "r" ) as zip_file: zip_file.extractall(UpperCAmelCase_ ) zip_file.close() class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : int = [b'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): with lzma.open(UpperCAmelCase_ ) as compressed_file: with open(UpperCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(UpperCAmelCase_ , UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = [b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): if not config.RARFILE_AVAILABLE: raise ImportError("Please pip install rarfile" ) import rarfile os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = rarfile.RarFile(UpperCAmelCase_ ) rf.extractall(UpperCAmelCase_ ) rf.close() class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : str = [b'''\x28\xb5\x2F\xFD'''] @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): if not config.ZSTANDARD_AVAILABLE: raise ImportError("Please pip install zstandard" ) import zstandard as zstd SCREAMING_SNAKE_CASE : Dict = zstd.ZstdDecompressor() with open(UpperCAmelCase_ , "rb" ) as ifh, open(UpperCAmelCase_ , "wb" ) as ofh: dctx.copy_stream(UpperCAmelCase_ , UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = [b'''\x42\x5A\x68'''] @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): with bza.open(UpperCAmelCase_ , "rb" ) as compressed_file: with open(UpperCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(UpperCAmelCase_ , UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = [b'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): if not config.PY7ZR_AVAILABLE: raise ImportError("Please pip install py7zr" ) import pyazr os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) with pyazr.SevenZipFile(UpperCAmelCase_ , "r" ) as archive: archive.extractall(UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = [b'''\x04\x22\x4D\x18'''] @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] ): if not config.LZ4_AVAILABLE: raise ImportError("Please pip install lz4" ) import lza.frame with lza.frame.open(UpperCAmelCase_ , "rb" ) as compressed_file: with open(UpperCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(UpperCAmelCase_ , UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE : '''simple docstring''' UpperCamelCase_ : Dict[str, Type[BaseExtractor]] = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def _A ( cls : Optional[Any] ): return max( len(UpperCAmelCase_ ) for extractor in cls.extractors.values() if issubclass(UpperCAmelCase_ , UpperCAmelCase_ ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def _A ( UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : int ): try: return MagicNumberBaseExtractor.read_magic_number(UpperCAmelCase_ , magic_number_length=UpperCAmelCase_ ) except OSError: return b"" @classmethod def _A ( cls : Any , UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : bool = False ): warnings.warn( "Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. " "Use 'infer_extractor_format' instead." , category=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = cls.infer_extractor_format(UpperCAmelCase_ ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def _A ( cls : List[Any] , UpperCAmelCase_ : Union[Path, str] ): # <Added version="2.4.0"/> SCREAMING_SNAKE_CASE : Optional[Any] = cls._get_magic_number_max_length() SCREAMING_SNAKE_CASE : Any = cls._read_magic_number(UpperCAmelCase_ , UpperCAmelCase_ ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(UpperCAmelCase_ , magic_number=UpperCAmelCase_ ): return extractor_format @classmethod def _A ( cls : Any , UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Union[Path, str] , UpperCAmelCase_ : Optional[str] = None , UpperCAmelCase_ : Optional[BaseExtractor] = "deprecated" , ): os.makedirs(os.path.dirname(UpperCAmelCase_ ) , exist_ok=UpperCAmelCase_ ) # Prevent parallel extractions SCREAMING_SNAKE_CASE : List[str] = str(Path(UpperCAmelCase_ ).with_suffix(".lock" ) ) with FileLock(UpperCAmelCase_ ): shutil.rmtree(UpperCAmelCase_ , ignore_errors=UpperCAmelCase_ ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # passed as positional arg warnings.warn( "Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. " "Use 'extractor_format' instead." , category=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Tuple = extractor if extractor != "deprecated" else extractor_format else: SCREAMING_SNAKE_CASE : Any = cls.extractors[extractor_format] return extractor.extract(UpperCAmelCase_ , UpperCAmelCase_ ) else: warnings.warn( "Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an " "exception in 3.0.0." , category=UpperCAmelCase_ , ) for extractor in cls.extractors.values(): if extractor.is_extractable(UpperCAmelCase_ ): return extractor.extract(UpperCAmelCase_ , UpperCAmelCase_ )
62
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ snake_case = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ snake_case = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _A ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def _A ( self : List[Any] , UpperCAmelCase_ : List[List[List[str]]] , UpperCAmelCase_ : List[List[str]] , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCAmelCase_ , hypotheses=UpperCAmelCase_ , min_len=UpperCAmelCase_ , max_len=UpperCAmelCase_ ) }
62
1
from __future__ import annotations def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): # noqa: E741 """simple docstring""" while r - l > 1: SCREAMING_SNAKE_CASE : List[str] = (l + r) // 2 if v[m] >= key: SCREAMING_SNAKE_CASE : Union[str, Any] = m else: SCREAMING_SNAKE_CASE : str = m # noqa: E741 return r def lowerCamelCase__ ( lowercase ): """simple docstring""" if len(lowercase ) == 0: return 0 SCREAMING_SNAKE_CASE : Dict = [0] * len(lowercase ) SCREAMING_SNAKE_CASE : Any = 1 SCREAMING_SNAKE_CASE : int = v[0] for i in range(1 , len(lowercase ) ): if v[i] < tail[0]: SCREAMING_SNAKE_CASE : str = v[i] elif v[i] > tail[length - 1]: SCREAMING_SNAKE_CASE : Dict = v[i] length += 1 else: SCREAMING_SNAKE_CASE : Any = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = row, column SCREAMING_SNAKE_CASE : Optional[Any] = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE : Optional[Any] = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = f'''%{max_element_length}s''' # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE : Optional[int] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Dict ): return str(self ) def _A ( self : Optional[int] , UpperCAmelCase_ : tuple[int, int] ): if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase_ : tuple[int, int] ): assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : int , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ): assert self.validate_indicies(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : Any = self[r, c] + another[r, c] return result def __neg__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ): return self + (-another) def __mul__( self : Dict , UpperCAmelCase_ : int | float | Matrix ): if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE : Any = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE : List[str] = f'''Unsupported type given for another ({type(UpperCAmelCase_ )})''' raise TypeError(UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : List[str] = self[r, c] return result def _A ( self : Union[str, Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE : Tuple = v.transpose() SCREAMING_SNAKE_CASE : int = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE : str = 1 print(F'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE : Optional[int] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 2, -3 SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase , lowercase )}''' ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() testa()
62
1
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = '''ssube/stable-diffusion-x4-upscaler-onnx''' def _A ( self : List[str] , UpperCAmelCase_ : Dict=0 ): SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, 3, 128, 128) , rng=random.Random(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : int = torch.manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(**UpperCAmelCase_ ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) SCREAMING_SNAKE_CASE : Any = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Tuple = pipe(**UpperCAmelCase_ ).images SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array( [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _A ( self : str ): SCREAMING_SNAKE_CASE : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) SCREAMING_SNAKE_CASE : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array( [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) SCREAMING_SNAKE_CASE : Any = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ ).images SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) SCREAMING_SNAKE_CASE : List[str] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = pipe(**UpperCAmelCase_ ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array( [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @property def _A ( self : List[str] ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Any = ort.SessionOptions() SCREAMING_SNAKE_CASE : Tuple = False return options def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) SCREAMING_SNAKE_CASE : Tuple = init_image.resize((128, 128) ) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE : int = OnnxStableDiffusionUpscalePipeline.from_pretrained( "ssube/stable-diffusion-x4-upscaler-onnx" , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = "A fantasy landscape, trending on artstation" SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe( prompt=UpperCAmelCase_ , image=UpperCAmelCase_ , guidance_scale=7.5 , num_inference_steps=10 , generator=UpperCAmelCase_ , output_type="np" , ) SCREAMING_SNAKE_CASE : Tuple = output.images SCREAMING_SNAKE_CASE : Union[str, Any] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) SCREAMING_SNAKE_CASE : Tuple = init_image.resize((128, 128) ) SCREAMING_SNAKE_CASE : int = LMSDiscreteScheduler.from_pretrained( "ssube/stable-diffusion-x4-upscaler-onnx" , subfolder="scheduler" ) SCREAMING_SNAKE_CASE : Any = OnnxStableDiffusionUpscalePipeline.from_pretrained( "ssube/stable-diffusion-x4-upscaler-onnx" , scheduler=UpperCAmelCase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = "A fantasy landscape, trending on artstation" SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe( prompt=UpperCAmelCase_ , image=UpperCAmelCase_ , guidance_scale=7.5 , num_inference_steps=20 , generator=UpperCAmelCase_ , output_type="np" , ) SCREAMING_SNAKE_CASE : Tuple = output.images SCREAMING_SNAKE_CASE : Tuple = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array( [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
62
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } snake_case = { """junnyu/roformer_chinese_small""": 1_536, """junnyu/roformer_chinese_base""": 1_536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } snake_case = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = RoFormerTokenizer def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : List[str]="[UNK]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : Any="[PAD]" , UpperCAmelCase_ : List[str]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : List[str] , ): 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_ , ) SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase_ ) != strip_accents ): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : List[str] = strip_accents SCREAMING_SNAKE_CASE : Tuple = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : Tuple , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = d SCREAMING_SNAKE_CASE : Dict = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE : Any = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase_ ) ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _A ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : List[Any] = [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 _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Optional[int] = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
62
1
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" def constraint_to_multiple_of(lowercase , lowercase , lowercase=0 , lowercase=None ): SCREAMING_SNAKE_CASE : Any = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : int = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Tuple = (output_size, output_size) if isinstance(lowercase , lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_image_size(lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Tuple = output_height / input_height SCREAMING_SNAKE_CASE : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width SCREAMING_SNAKE_CASE : List[str] = scale_width else: # fit height SCREAMING_SNAKE_CASE : Optional[Any] = scale_height SCREAMING_SNAKE_CASE : int = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase ) SCREAMING_SNAKE_CASE : Dict = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase ) return (new_height, new_width) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase_ : str , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = size if size is not None else {"height": 384, "width": 384} SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : int = ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample SCREAMING_SNAKE_CASE : List[str] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self : Tuple , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : int , ): SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = get_resize_output_image_size( UpperCAmelCase_ , output_size=(size["height"], size["width"]) , keep_aspect_ratio=UpperCAmelCase_ , multiple=UpperCAmelCase_ , ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Dict , ): return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ): return normalize(UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : Optional[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : List[str] = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Any = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Tuple = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Tuple = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Tuple] = None ): SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : str = [] for idx in range(len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
62
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE : Optional[int] = str(abs(lowercase ) ) SCREAMING_SNAKE_CASE : str = [list(lowercase ) for char in range(len(lowercase ) )] for index in range(len(lowercase ) ): num_transpositions[index].pop(lowercase ) return max( int("".join(list(lowercase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
62
1
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE : Optional[int] = str(abs(lowercase ) ) SCREAMING_SNAKE_CASE : str = [list(lowercase ) for char in range(len(lowercase ) )] for index in range(len(lowercase ) ): num_transpositions[index].pop(lowercase ) return max( int("".join(list(lowercase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
62
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = 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 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : int ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) 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 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _A ( self : Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9E-2
62
1
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [1] for i in range(2 , lowercase ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE : Any = [] SCREAMING_SNAKE_CASE : Dict = list(range(lowercase ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE : List[str] = factorials.pop() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = divmod(lowercase , lowercase ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
62
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 ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE : List[Any] = [144, 192, 240] SCREAMING_SNAKE_CASE : Tuple = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [96, 120, 144] SCREAMING_SNAKE_CASE : Dict = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [64, 80, 96] SCREAMING_SNAKE_CASE : List[str] = [16, 16, 24, 48, 64, 80, 320] SCREAMING_SNAKE_CASE : int = 0.05 SCREAMING_SNAKE_CASE : int = 2.0 if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : str = 512 SCREAMING_SNAKE_CASE : List[str] = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 21 SCREAMING_SNAKE_CASE : Dict = "pascal-voc-id2label.json" else: SCREAMING_SNAKE_CASE : Optional[Any] = 1000 SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : Any = "huggingface/label-files" SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowercase , lowercase , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE : List[str] = {int(lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} return config def lowerCamelCase__ ( lowercase , lowercase=False ): """simple docstring""" for i in range(1 , 6 ): if F'''layer_{i}.''' in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(F'''layer_{i}.''' , F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: SCREAMING_SNAKE_CASE : Dict = name.replace("conv_1." , "conv_stem." ) if ".block." in name: SCREAMING_SNAKE_CASE : List[str] = name.replace(".block." , "." ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE : str = name.replace("exp_1x1" , "expand_1x1" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("red_1x1" , "reduce_1x1" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".local_rep.conv_3x3." , ".conv_kxk." ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE : int = name.replace(".local_rep.conv_1x1." , ".conv_1x1." ) if ".norm." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".norm." , ".normalization." ) if ".conv." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".conv." , ".convolution." ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".conv_proj." , ".conv_projection." ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.layer.{j}.''' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.''' ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("expand_1x1" , "downsampling_layer.expand_1x1" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE : str = name.replace("conv_3x3" , "downsampling_layer.conv_3x3" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("reduce_1x1" , "downsampling_layer.reduce_1x1" ) for i in range(2 , 5 ): if F'''.global_rep.{i}.weight''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.global_rep.{i}.weight''' , ".layernorm.weight" ) if F'''.global_rep.{i}.bias''' in name: SCREAMING_SNAKE_CASE : str = name.replace(F'''.global_rep.{i}.bias''' , ".layernorm.bias" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".global_rep." , ".transformer." ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_mha.0." , ".layernorm_before." ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_mha.1.out_proj." , ".attention.output.dense." ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(".pre_norm_ffn.0." , ".layernorm_after." ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_ffn.1." , ".intermediate.dense." ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_ffn.4." , ".output.dense." ) if ".transformer." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".transformer." , ".transformer.layer." ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE : int = name.replace(".aspp_layer." , "." ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".aspp_pool." , "." ) if "seg_head." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("seg_head." , "segmentation_head." ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("segmentation_head.classifier.classifier." , "segmentation_head.classifier." ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("classifier.fc." , "classifier." ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE : List[Any] = "mobilevit." + name return name def lowerCamelCase__ ( lowercase , lowercase , lowercase=False ): """simple docstring""" if base_model: SCREAMING_SNAKE_CASE : Optional[int] = "" else: SCREAMING_SNAKE_CASE : Any = "mobilevit." for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = orig_state_dict.pop(lowercase ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE : int = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.split("." ) SCREAMING_SNAKE_CASE : Any = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE : List[Any] = int(key_split[3] ) SCREAMING_SNAKE_CASE : List[Any] = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) SCREAMING_SNAKE_CASE : int = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE : Union[str, Any] = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: SCREAMING_SNAKE_CASE : str = val[:dim] SCREAMING_SNAKE_CASE : Union[str, Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] else: SCREAMING_SNAKE_CASE : List[Any] = val return orig_state_dict def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_mobilevit_config(lowercase ) # load original state_dict SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(lowercase , map_location="cpu" ) # load 🤗 model if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : List[str] = MobileViTForSemanticSegmentation(lowercase ).eval() else: SCREAMING_SNAKE_CASE : str = MobileViTForImageClassification(lowercase ).eval() SCREAMING_SNAKE_CASE : Any = convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE : List[Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE : List[Any] = model(**lowercase ) SCREAMING_SNAKE_CASE : str = outputs.logits if mobilevit_name.startswith("deeplabv3_" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] , lowercase , atol=1E-4 ) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE : Dict = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] , lowercase , atol=1E-4 ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if push_to_hub: SCREAMING_SNAKE_CASE : List[str] = { "mobilevit_s": "mobilevit-small", "mobilevit_xs": "mobilevit-x-small", "mobilevit_xxs": "mobilevit-xx-small", "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small", "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small", "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small", } print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE : int = model_mapping[mobilevit_name] image_processor.push_to_hub(lowercase , organization="apple" ) model.push_to_hub(lowercase , organization="apple" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, 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 = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
62
1
import math def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Union[str, Any] = 2 SCREAMING_SNAKE_CASE : List[str] = int(math.sqrt(lowercase ) ) # Size of every segment SCREAMING_SNAKE_CASE : str = [True] * (end + 1) SCREAMING_SNAKE_CASE : Dict = [] while start <= end: if temp[start] is True: in_prime.append(lowercase ) for i in range(start * start , end + 1 , lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = False start += 1 prime += in_prime SCREAMING_SNAKE_CASE : Union[str, Any] = end + 1 SCREAMING_SNAKE_CASE : Optional[Any] = min(2 * end , lowercase ) while low <= n: SCREAMING_SNAKE_CASE : Dict = [True] * (high - low + 1) for each in in_prime: SCREAMING_SNAKE_CASE : Tuple = math.floor(low / each ) * each if t < low: t += each for j in range(lowercase , high + 1 , lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = False for j in range(len(lowercase ) ): if temp[j] is True: prime.append(j + low ) SCREAMING_SNAKE_CASE : str = high + 1 SCREAMING_SNAKE_CASE : List[Any] = min(high + end , lowercase ) return prime print(sieve(10**6))
62
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case = datasets.load_iris() snake_case = np.array(data["""data"""]) snake_case = np.array(data["""target"""]) snake_case = data["""target_names"""] snake_case , snake_case , snake_case , snake_case = train_test_split(X, y) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase=5 ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = zip(lowercase , lowercase ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE : Optional[int] = [] for data_point in data: SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE : List[Any] = [i[1] for i in sorted(lowercase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE : List[Any] = Counter(lowercase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
62
1
def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = 0 for ch in input_str: SCREAMING_SNAKE_CASE : Any = ord(lowercase ) SCREAMING_SNAKE_CASE : Tuple = pow(2 , lowercase ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
62
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''xlm-prophetnet''' UpperCamelCase_ : Tuple = ['''past_key_values'''] UpperCamelCase_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Dict , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[Union[str, Callable]] = "gelu" , UpperCAmelCase_ : Optional[int] = 3_0522 , UpperCAmelCase_ : Optional[int] = 1024 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[int] = 512 , UpperCAmelCase_ : Optional[float] = 0.02 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 2 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 128 , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[float] = 0.0 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 2 , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = num_encoder_layers SCREAMING_SNAKE_CASE : Any = num_encoder_attention_heads SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers SCREAMING_SNAKE_CASE : List[Any] = num_decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE : Dict = ngram SCREAMING_SNAKE_CASE : Any = num_buckets SCREAMING_SNAKE_CASE : str = relative_max_distance SCREAMING_SNAKE_CASE : str = disable_ngram_loss SCREAMING_SNAKE_CASE : Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : int = use_cache super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , add_cross_attention=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def _A ( self : int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
62
1
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase="attention" ): """simple docstring""" SCREAMING_SNAKE_CASE : int = params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel'''] SCREAMING_SNAKE_CASE : List[str] = params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel'''] SCREAMING_SNAKE_CASE : Union[str, Any] = params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel'''] SCREAMING_SNAKE_CASE : Optional[int] = params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel'''] return k, o, q, v def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" if split_mlp_wi: SCREAMING_SNAKE_CASE : Any = params[F'''{prefix}/layers_{i}/mlp/wi_0/kernel'''] SCREAMING_SNAKE_CASE : List[Any] = params[F'''{prefix}/layers_{i}/mlp/wi_1/kernel'''] SCREAMING_SNAKE_CASE : str = (wi_a, wi_a) else: SCREAMING_SNAKE_CASE : Any = params[F'''{prefix}/layers_{i}/mlp/wi/kernel'''] SCREAMING_SNAKE_CASE : int = params[F'''{prefix}/layers_{i}/mlp/wo/kernel'''] return wi, wo def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" return params[F'''{prefix}/layers_{i}/{layer_name}/scale'''] def lowerCamelCase__ ( lowercase , *, lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = traverse_util.flatten_dict(variables["target"] ) SCREAMING_SNAKE_CASE : Union[str, Any] = {"/".join(lowercase ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi SCREAMING_SNAKE_CASE : Dict = "encoder/layers_0/mlp/wi_0/kernel" in old print("Split MLP:" , lowercase ) SCREAMING_SNAKE_CASE : Tuple = collections.OrderedDict() # Shared embeddings. SCREAMING_SNAKE_CASE : Tuple = old["token_embedder/embedding"] # Encoder. for i in range(lowercase ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE : Optional[int] = tax_layer_norm_lookup(lowercase , lowercase , "encoder" , "pre_attention_layer_norm" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = tax_attention_lookup(lowercase , lowercase , "encoder" , "attention" ) SCREAMING_SNAKE_CASE : List[Any] = layer_norm SCREAMING_SNAKE_CASE : Optional[int] = k.T SCREAMING_SNAKE_CASE : List[str] = o.T SCREAMING_SNAKE_CASE : Optional[int] = q.T SCREAMING_SNAKE_CASE : List[str] = v.T # Block i, layer 1 (MLP). SCREAMING_SNAKE_CASE : Tuple = tax_layer_norm_lookup(lowercase , lowercase , "encoder" , "pre_mlp_layer_norm" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = tax_mlp_lookup(lowercase , lowercase , "encoder" , lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE : Tuple = wi[0].T SCREAMING_SNAKE_CASE : Optional[Any] = wi[1].T else: SCREAMING_SNAKE_CASE : Optional[int] = wi.T SCREAMING_SNAKE_CASE : Optional[int] = wo.T SCREAMING_SNAKE_CASE : Union[str, Any] = old[ "encoder/relpos_bias/rel_embedding" ].T SCREAMING_SNAKE_CASE : List[str] = old["encoder/encoder_norm/scale"] if not is_encoder_only: # Decoder. for i in range(lowercase ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE : int = tax_layer_norm_lookup(lowercase , lowercase , "decoder" , "pre_self_attention_layer_norm" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = tax_attention_lookup(lowercase , lowercase , "decoder" , "self_attention" ) SCREAMING_SNAKE_CASE : str = layer_norm SCREAMING_SNAKE_CASE : Optional[int] = k.T SCREAMING_SNAKE_CASE : int = o.T SCREAMING_SNAKE_CASE : Optional[int] = q.T SCREAMING_SNAKE_CASE : Union[str, Any] = v.T # Block i, layer 1 (Cross Attention). SCREAMING_SNAKE_CASE : List[str] = tax_layer_norm_lookup(lowercase , lowercase , "decoder" , "pre_cross_attention_layer_norm" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = tax_attention_lookup(lowercase , lowercase , "decoder" , "encoder_decoder_attention" ) SCREAMING_SNAKE_CASE : int = layer_norm SCREAMING_SNAKE_CASE : Optional[Any] = k.T SCREAMING_SNAKE_CASE : Any = o.T SCREAMING_SNAKE_CASE : Any = q.T SCREAMING_SNAKE_CASE : Tuple = v.T # Block i, layer 2 (MLP). SCREAMING_SNAKE_CASE : int = tax_layer_norm_lookup(lowercase , lowercase , "decoder" , "pre_mlp_layer_norm" ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = tax_mlp_lookup(lowercase , lowercase , "decoder" , lowercase ) SCREAMING_SNAKE_CASE : Any = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE : Union[str, Any] = wi[0].T SCREAMING_SNAKE_CASE : Dict = wi[1].T else: SCREAMING_SNAKE_CASE : str = wi.T SCREAMING_SNAKE_CASE : List[str] = wo.T SCREAMING_SNAKE_CASE : Dict = old["decoder/decoder_norm/scale"] SCREAMING_SNAKE_CASE : Optional[Any] = old[ "decoder/relpos_bias/rel_embedding" ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: SCREAMING_SNAKE_CASE : Any = old["decoder/logits_dense/kernel"].T return new def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE : str = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE : Dict = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("Using shared word embeddings as lm_head." ) SCREAMING_SNAKE_CASE : Optional[int] = state_dict["shared.weight"] return state_dict def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = checkpoints.load_tax_checkpoint(lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = convert_tax_to_pytorch(lowercase , num_layers=config.num_layers , is_encoder_only=lowercase ) SCREAMING_SNAKE_CASE : Tuple = make_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase , strict=lowercase ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase = False ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = TaConfig.from_json_file(lowercase ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: SCREAMING_SNAKE_CASE : Union[str, Any] = TaEncoderModel(lowercase ) else: SCREAMING_SNAKE_CASE : List[Any] = TaForConditionalGeneration(lowercase ) # Load weights from tf checkpoint load_tax_weights_in_ta(lowercase , lowercase , lowercase , lowercase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowercase ) # Verify that we can load the checkpoint. model.from_pretrained(lowercase ) print("Done" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser(description="""Converts a native T5X checkpoint into a PyTorch checkpoint.""") # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path to the T5X checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained T5 model.\nThis 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_encoder_only""", action="""store_true""", help="""Check if the model is encoder-decoder model""", default=False ) snake_case = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
62
import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, 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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = KandinskyVaaPipeline UpperCamelCase_ : List[Any] = [ '''image_embeds''', '''negative_image_embeds''', ] UpperCamelCase_ : Tuple = ['''image_embeds''', '''negative_image_embeds'''] UpperCamelCase_ : Any = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCamelCase_ : List[str] = False @property def _A ( self : List[Any] ): return 32 @property def _A ( self : List[Any] ): return 32 @property def _A ( self : Any ): return self.time_input_dim @property def _A ( self : Union[str, Any] ): return self.time_input_dim * 4 @property def _A ( self : Tuple ): return 100 @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } SCREAMING_SNAKE_CASE : str = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def _A ( self : int ): 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 : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = self.dummy_unet SCREAMING_SNAKE_CASE : str = self.dummy_movq SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="epsilon" , thresholding=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _A ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]=0 ): SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = "cpu" SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : Tuple = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array( [0.6_237_976, 1.0, 0.36_441_332, 1.0, 0.70_639_634, 0.29_877_186, 0.85_652_125, 0.5_216_843, 0.54_454_046] ) 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy" ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Tuple = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = "red cat, 4k photo" SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="np" , ) SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
62
1
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class SCREAMING_SNAKE_CASE : '''simple docstring''' UpperCamelCase_ : List[Any] = LEDConfig UpperCamelCase_ : Tuple = {} UpperCamelCase_ : Dict = '''gelu''' def __init__( self : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Optional[int]=2 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Union[str, Any]=37 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : List[str]=20 , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : Optional[int]=1 , UpperCAmelCase_ : Optional[Any]=0 , UpperCAmelCase_ : Tuple=4 , ): SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : List[str] = batch_size SCREAMING_SNAKE_CASE : Any = seq_length SCREAMING_SNAKE_CASE : Optional[Any] = is_training SCREAMING_SNAKE_CASE : int = use_labels SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Any = max_position_embeddings SCREAMING_SNAKE_CASE : str = eos_token_id SCREAMING_SNAKE_CASE : int = pad_token_id SCREAMING_SNAKE_CASE : Optional[Any] = bos_token_id SCREAMING_SNAKE_CASE : Optional[Any] = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after SCREAMING_SNAKE_CASE : List[Any] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests SCREAMING_SNAKE_CASE : Dict = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) SCREAMING_SNAKE_CASE : int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) SCREAMING_SNAKE_CASE : int = tf.concat([input_ids, eos_tensor] , axis=1 ) SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = 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 , attention_window=self.attention_window , **self.config_updates , ) SCREAMING_SNAKE_CASE : Tuple = prepare_led_inputs_dict(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = tf.concat( [tf.zeros_like(UpperCAmelCase_ )[:, :-1], tf.ones_like(UpperCAmelCase_ )[:, -1:]] , axis=-1 , ) SCREAMING_SNAKE_CASE : int = global_attention_mask return config, inputs_dict def _A ( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : str = TFLEDModel(config=UpperCAmelCase_ ).get_decoder() SCREAMING_SNAKE_CASE : str = inputs_dict["input_ids"] SCREAMING_SNAKE_CASE : List[str] = input_ids[:1, :] SCREAMING_SNAKE_CASE : Any = inputs_dict["attention_mask"][:1, :] SCREAMING_SNAKE_CASE : Union[str, Any] = 1 # first forward pass SCREAMING_SNAKE_CASE : Dict = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , use_cache=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE : str = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE : Optional[int] = tf.concat([input_ids, next_tokens] , axis=-1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) SCREAMING_SNAKE_CASE : Dict = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : str = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE : Dict = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE : List[str] = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE : str = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(UpperCAmelCase_ , UpperCAmelCase_ , rtol=1E-3 ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=None , lowercase=None , lowercase=None , lowercase=None , ): """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE : Tuple = tf.cast(tf.math.not_equal(lowercase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE : Union[str, Any] = 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: SCREAMING_SNAKE_CASE : Union[str, Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE : Optional[int] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () UpperCamelCase_ : List[str] = (TFLEDForConditionalGeneration,) if is_tf_available() else () UpperCamelCase_ : int = ( { '''conversational''': TFLEDForConditionalGeneration, '''feature-extraction''': TFLEDModel, '''summarization''': TFLEDForConditionalGeneration, '''text2text-generation''': TFLEDForConditionalGeneration, '''translation''': TFLEDForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase_ : Union[str, Any] = True UpperCamelCase_ : int = False UpperCamelCase_ : int = False UpperCamelCase_ : Union[str, Any] = False def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Tuple = TFLEDModelTester(self ) SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=UpperCAmelCase_ ) def _A ( self : Optional[int] ): self.config_tester.run_common_tests() def _A ( self : int ): SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : Optional[Any] = tf.zeros_like(inputs_dict["attention_mask"] ) SCREAMING_SNAKE_CASE : Tuple = 2 SCREAMING_SNAKE_CASE : List[Any] = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) SCREAMING_SNAKE_CASE : Tuple = True SCREAMING_SNAKE_CASE : Dict = self.model_tester.seq_length SCREAMING_SNAKE_CASE : List[str] = self.model_tester.encoder_seq_length def check_decoder_attentions_output(UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.decoder_attentions self.assertEqual(len(UpperCAmelCase_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = [t.numpy() for t in outputs.encoder_attentions] SCREAMING_SNAKE_CASE : List[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(UpperCAmelCase_ ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(UpperCAmelCase_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Union[str, Any] = True SCREAMING_SNAKE_CASE : str = False SCREAMING_SNAKE_CASE : str = False SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = len(UpperCAmelCase_ ) self.assertEqual(config.output_hidden_states , UpperCAmelCase_ ) check_encoder_attentions_output(UpperCAmelCase_ ) if self.is_encoder_decoder: SCREAMING_SNAKE_CASE : Dict = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = model(self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertEqual(config.output_hidden_states , UpperCAmelCase_ ) check_decoder_attentions_output(UpperCAmelCase_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE : int = True SCREAMING_SNAKE_CASE : List[Any] = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = model(self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertEqual(config.output_hidden_states , UpperCAmelCase_ ) check_encoder_attentions_output(UpperCAmelCase_ ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE : Tuple = True SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Optional[Any] = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = model(self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(UpperCAmelCase_ ) ) self.assertEqual(model.config.output_hidden_states , UpperCAmelCase_ ) check_encoder_attentions_output(UpperCAmelCase_ ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def _A ( self : List[Any] ): pass def _A ( self : Optional[Any] ): # TODO: Head-masking not yet implement pass def lowerCamelCase__ ( lowercase ): """simple docstring""" return tf.constant(lowercase , dtype=tf.intaa ) snake_case = 1e-4 @slow @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here SCREAMING_SNAKE_CASE : List[str] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) SCREAMING_SNAKE_CASE : Dict = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) SCREAMING_SNAKE_CASE : List[Any] = prepare_led_inputs_dict(model.config , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = model(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : int = (1, 1024, 768) self.assertEqual(output.shape , UpperCAmelCase_ ) # change to expected output here SCREAMING_SNAKE_CASE : Union[str, Any] = tf.convert_to_tensor( [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-3 ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here SCREAMING_SNAKE_CASE : Any = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) SCREAMING_SNAKE_CASE : Optional[int] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) SCREAMING_SNAKE_CASE : List[Any] = prepare_led_inputs_dict(model.config , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = model(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Any = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , UpperCAmelCase_ ) # change to expected output here SCREAMING_SNAKE_CASE : Tuple = tf.convert_to_tensor( [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-3 , rtol=1E-3 )
62
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput snake_case = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : int , *UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Tuple=None , **UpperCAmelCase_ : Optional[Any] ): super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = eval_examples SCREAMING_SNAKE_CASE : List[Any] = post_process_function SCREAMING_SNAKE_CASE : Any = quant_trainer_args SCREAMING_SNAKE_CASE : Optional[Any] = 128 # default number of calibration samples def _A ( self : Optional[Any] , UpperCAmelCase_ : Tuple=None ): if calib_dataset is None and self.calib_dataset is None: raise ValueError("Trainer: calibration requires an calib_dataset." ) SCREAMING_SNAKE_CASE : str = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE : str = self._remove_unused_columns(UpperCAmelCase_ , description="Calibration" ) return DataLoader( UpperCAmelCase_ , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=UpperCAmelCase_ , ) def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[int]=None ): SCREAMING_SNAKE_CASE : Any = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_calib_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args , calib=UpperCAmelCase_ ) model.eval() quant_trainer.enable_calibration(UpperCAmelCase_ ) logger.info("***** Running calibration *****" ) logger.info(f''' Num examples = {self.calib_num}''' ) logger.info(f''' Batch size = {calib_dataloader.batch_size}''' ) for step, inputs in enumerate(UpperCAmelCase_ ): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.prediction_step(UpperCAmelCase_ , UpperCAmelCase_ , prediction_loss_only=UpperCAmelCase_ ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : Optional[int] = model def _A ( self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str = "eval" ): SCREAMING_SNAKE_CASE : List[str] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : Tuple = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : int = eval_loop( UpperCAmelCase_ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : int = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE : List[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions ) SCREAMING_SNAKE_CASE : Any = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = metrics.pop(UpperCAmelCase_ ) self.log(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : List[Any] = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : List[str] = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCAmelCase_ ) return metrics def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : str = "test" ): SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(UpperCAmelCase_ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Tuple = self.compute_metrics SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : str = eval_loop( UpperCAmelCase_ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : Union[str, Any] = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Optional[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions , "predict" ) SCREAMING_SNAKE_CASE : str = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : str = metrics.pop(UpperCAmelCase_ ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCAmelCase_ ) def _A ( self : Any , UpperCAmelCase_ : int="./" ): SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = next(iter(UpperCAmelCase_ ) ) # saving device - to make it consistent SCREAMING_SNAKE_CASE : int = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) # convert to tuple SCREAMING_SNAKE_CASE : Tuple = tuple(v.to(UpperCAmelCase_ ) for k, v in batch.items() ) logger.info("Converting model to be onnx compatible" ) from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Any = self.model.to(UpperCAmelCase_ ) model.eval() model.float() SCREAMING_SNAKE_CASE : str = model.module if hasattr(UpperCAmelCase_ , "module" ) else model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : List[Any] = os.path.join(UpperCAmelCase_ , "model.onnx" ) logger.info(f'''exporting model to {output_model_file}''' ) SCREAMING_SNAKE_CASE : int = {0: "batch_size", 1: "seq_len"} torch.onnx.export( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , export_params=UpperCAmelCase_ , opset_version=13 , do_constant_folding=UpperCAmelCase_ , input_names=["input_ids", "attention_mask", "token_type_ids"] , output_names=["output_start_logits", "output_end_logits"] , dynamic_axes={ "input_ids": axes, "attention_mask": axes, "token_type_ids": axes, "output_start_logits": axes, "output_end_logits": axes, } , verbose=UpperCAmelCase_ , ) logger.info("onnx export finished" )
62
1
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = row, column SCREAMING_SNAKE_CASE : Optional[Any] = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE : Optional[Any] = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = f'''%{max_element_length}s''' # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE : Optional[int] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Dict ): return str(self ) def _A ( self : Optional[int] , UpperCAmelCase_ : tuple[int, int] ): if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase_ : tuple[int, int] ): assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : int , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ): assert self.validate_indicies(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : Any = self[r, c] + another[r, c] return result def __neg__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ): return self + (-another) def __mul__( self : Dict , UpperCAmelCase_ : int | float | Matrix ): if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE : Any = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE : List[str] = f'''Unsupported type given for another ({type(UpperCAmelCase_ )})''' raise TypeError(UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : List[str] = self[r, c] return result def _A ( self : Union[str, Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE : Tuple = v.transpose() SCREAMING_SNAKE_CASE : int = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE : str = 1 print(F'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE : Optional[int] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 2, -3 SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase , lowercase )}''' ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() testa()
62
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = LayoutLMTokenizer UpperCamelCase_ : str = LayoutLMTokenizerFast UpperCamelCase_ : Any = True UpperCamelCase_ : Optional[Any] = True def _A ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : str , **UpperCAmelCase_ : Optional[int] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Any = "UNwant\u00E9d,running" SCREAMING_SNAKE_CASE : Union[str, Any] = "unwanted, running" return input_text, output_text def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [7, 4, 5, 10, 8, 9] ) def _A ( self : List[str] ): pass
62
1
import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold 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, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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__ ( lowercase , lowercase , lowercase , lowercase , lowercase = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE : Optional[Any] = DatasetDict( { "train": dataset["train"].select(lowercase ), "validation": dataset["train"].select(lowercase ), "test": dataset["validation"], } ) def tokenize_function(lowercase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowercase , max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE : Tuple = datasets.map( lowercase , batched=lowercase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE : str = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE : Union[str, Any] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE : Optional[Any] = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE : Tuple = 8 else: SCREAMING_SNAKE_CASE : Dict = None return tokenizer.pad( lowercase , padding="longest" , max_length=lowercase , pad_to_multiple_of=lowercase , return_tensors="pt" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE : int = DataLoader( tokenized_datasets["train"] , shuffle=lowercase , collate_fn=lowercase , batch_size=lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = DataLoader( tokenized_datasets["validation"] , shuffle=lowercase , collate_fn=lowercase , batch_size=lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = DataLoader( tokenized_datasets["test"] , shuffle=lowercase , collate_fn=lowercase , batch_size=lowercase ) return train_dataloader, eval_dataloader, test_dataloader def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [] # Download the dataset SCREAMING_SNAKE_CASE : int = load_dataset("glue" , "mrpc" ) # Create our splits SCREAMING_SNAKE_CASE : List[str] = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator SCREAMING_SNAKE_CASE : List[Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE : Optional[Any] = config["lr"] SCREAMING_SNAKE_CASE : Union[str, Any] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE : int = int(config["seed"] ) SCREAMING_SNAKE_CASE : str = int(config["batch_size"] ) SCREAMING_SNAKE_CASE : List[Any] = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE : List[str] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE : List[str] = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE : Optional[int] = MAX_GPU_BATCH_SIZE set_seed(lowercase ) # New Code # # Create our folds: SCREAMING_SNAKE_CASE : List[Any] = kfold.split(np.zeros(datasets["train"].num_rows ) , datasets["train"]["label"] ) SCREAMING_SNAKE_CASE : Any = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = get_fold_dataloaders( lowercase , lowercase , lowercase , lowercase , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE : Any = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowercase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE : Union[str, Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE : str = AdamW(params=model.parameters() , lr=lowercase ) # Instantiate scheduler SCREAMING_SNAKE_CASE : Dict = get_linear_schedule_with_warmup( optimizer=lowercase , num_warmup_steps=100 , num_training_steps=(len(lowercase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = accelerator.prepare( lowercase , lowercase , lowercase , lowercase , lowercase ) # Now we train the model for epoch in range(lowercase ): model.train() for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE : List[Any] = model(**lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.loss SCREAMING_SNAKE_CASE : Any = loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowercase , references=lowercase , ) SCREAMING_SNAKE_CASE : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , lowercase ) # New Code # # We also run predictions on the test set at the very end SCREAMING_SNAKE_CASE : Optional[Any] = [] for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**lowercase ) SCREAMING_SNAKE_CASE : int = outputs.logits SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(lowercase , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat(lowercase , dim=0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.stack(lowercase , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) SCREAMING_SNAKE_CASE : int = metric.compute(predictions=lowercase , references=lowercase ) accelerator.print("Average test metrics from all folds:" , lowercase ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowercase , default=lowercase , 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." ) # New Code # parser.add_argument("--num_folds" , type=lowercase , default=3 , help="The number of splits to perform across the dataset" ) SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE : List[Any] = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowercase , lowercase ) if __name__ == "__main__": main()
62
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = os.path.join(args.tf_model_dir , "parameters.json" ) SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(open(lowercase ).read() ) if not params: raise ValueError( F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.''' ) if not args.output.endswith(".pt" ): SCREAMING_SNAKE_CASE : Optional[int] = args.output + ".pt" SCREAMING_SNAKE_CASE : Any = OrderedDict() with tf.device("/CPU:0" ): SCREAMING_SNAKE_CASE : Union[str, Any] = tf.train.load_checkpoint(args.tf_model_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): SCREAMING_SNAKE_CASE : Any = reader.get_tensor(lowercase ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9] ) elif key_name.startswith("pasts/out" ): SCREAMING_SNAKE_CASE : Optional[int] = 8 SCREAMING_SNAKE_CASE : List[Any] = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time SCREAMING_SNAKE_CASE : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.startswith("model/moe" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/softmlp/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): SCREAMING_SNAKE_CASE : Optional[int] = key_name[-9:-7] for i in range(16 ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) SCREAMING_SNAKE_CASE : List[str] = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name.startswith("model/mlp" ): SCREAMING_SNAKE_CASE : str = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.mlp.wi.weight" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/p1/bias" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.wi.bias" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/kernel" ): SCREAMING_SNAKE_CASE : str = "model.blocks.%d.feed_forward.mlp.wo.weight" % player SCREAMING_SNAKE_CASE : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/bias" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.feed_forward.mlp.wo.bias" % player SCREAMING_SNAKE_CASE : str = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) elif key_name.startswith("model/ln" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.norm.bias" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : List[str] = "model.blocks.%d.feed_forward.norm.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/att" ): SCREAMING_SNAKE_CASE : Optional[int] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum SCREAMING_SNAKE_CASE : List[str] = state[:, 0, :, :] SCREAMING_SNAKE_CASE : Tuple = state[:, 1, :, :] SCREAMING_SNAKE_CASE : List[Any] = state[:, 2, :, :] SCREAMING_SNAKE_CASE : Tuple = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : int = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/o/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif key_name.startswith("model/an" ): SCREAMING_SNAKE_CASE : int = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.self_attn.norm.bias" % player SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.self_attn.norm.weight" % player SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): SCREAMING_SNAKE_CASE : str = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] SCREAMING_SNAKE_CASE : List[str] = "model.%s.weight" % nlayer SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) if key_name.startswith("model/wte" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "lm_head.weight" SCREAMING_SNAKE_CASE : List[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/wob" ): SCREAMING_SNAKE_CASE : List[Any] = "final_logits_bias" SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : List[str] = state.reshape((1, -1) ) SCREAMING_SNAKE_CASE : int = torch.tensor(lowercase ) elif key_name == "model/dense/kernel": SCREAMING_SNAKE_CASE : Optional[int] = "model.last_project.weight" SCREAMING_SNAKE_CASE : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name == "model/dense_1/bias": SCREAMING_SNAKE_CASE : str = "model.last_project.bias" SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) torch.save(lowercase , args.output ) if __name__ == "__main__": snake_case = argparse.ArgumentParser( description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""") parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""") snake_case = parser.parse_args() convert_tf_gptsan_to_pt(args)
62
1
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''xlm-prophetnet''' UpperCamelCase_ : Tuple = ['''past_key_values'''] UpperCamelCase_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Dict , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[Union[str, Callable]] = "gelu" , UpperCAmelCase_ : Optional[int] = 3_0522 , UpperCAmelCase_ : Optional[int] = 1024 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[int] = 512 , UpperCAmelCase_ : Optional[float] = 0.02 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 2 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 128 , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[float] = 0.0 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 2 , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = num_encoder_layers SCREAMING_SNAKE_CASE : Any = num_encoder_attention_heads SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers SCREAMING_SNAKE_CASE : List[Any] = num_decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE : Dict = ngram SCREAMING_SNAKE_CASE : Any = num_buckets SCREAMING_SNAKE_CASE : str = relative_max_distance SCREAMING_SNAKE_CASE : str = disable_ngram_loss SCREAMING_SNAKE_CASE : Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : int = use_cache super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , add_cross_attention=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def _A ( self : int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
62
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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: on SCREAMING_SNAKE_CASE : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Optional[int] = { "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], } SCREAMING_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 _A ( self : List[Any] , **UpperCAmelCase_ : List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Union[str, Any] , **UpperCAmelCase_ : Any ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Union[str, Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE : Any = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) SCREAMING_SNAKE_CASE : str = 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 _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : int = image_processor(UpperCAmelCase_ , return_tensors="np" ) SCREAMING_SNAKE_CASE : Optional[int] = 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 _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = "lower newer" SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : int = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = "lower newer" SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = 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 _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Optional[Any] = processor.batch_decode(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = "lower newer" SCREAMING_SNAKE_CASE : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
62
1
import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = ['''image_processor''', '''tokenizer'''] UpperCamelCase_ : str = '''FlavaImageProcessor''' UpperCamelCase_ : Union[str, Any] = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : List[str] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[int]=None , **UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : str = kwargs.pop("feature_extractor" ) SCREAMING_SNAKE_CASE : Optional[int] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.image_processor def __call__( self : str , UpperCAmelCase_ : Optional[ImageInput] = None , UpperCAmelCase_ : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_ : Union[bool, str, TruncationStrategy] = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase_ : str , ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: SCREAMING_SNAKE_CASE : str = self.tokenizer( text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , stride=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_overflowing_tokens=UpperCAmelCase_ , return_special_tokens_mask=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , return_length=UpperCAmelCase_ , verbose=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) if images is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor( UpperCAmelCase_ , return_image_mask=UpperCAmelCase_ , return_codebook_pixels=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) if text is not None and images is not None: encoding.update(UpperCAmelCase_ ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_ ) , tensor_type=UpperCAmelCase_ ) def _A ( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[str] ): return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Union[str, Any] ): return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) @property def _A ( self : Any ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _A ( self : str ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class @property def _A ( self : Union[str, Any] ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , UpperCAmelCase_ , ) return self.image_processor
62
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "tf_padding" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "depth_multiplier" ) ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]=13 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : int=0.25 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : Dict=8 , UpperCAmelCase_ : Optional[int]=6 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : str="relu6" , UpperCAmelCase_ : List[str]=1280 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : int = depth_multiplier SCREAMING_SNAKE_CASE : str = depth_divisible_by SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth SCREAMING_SNAKE_CASE : int = expand_ratio SCREAMING_SNAKE_CASE : Tuple = tf_padding SCREAMING_SNAKE_CASE : List[str] = output_stride SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion SCREAMING_SNAKE_CASE : Any = finegrained_output SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = scope def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels, pixel_labels def _A ( self : Optional[int] ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Dict = MobileNetVaForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase_ : List[Any] = ( { '''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification, '''image-segmentation''': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Any = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : int = False UpperCamelCase_ : str = False def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def _A ( self : List[Any] ): pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def _A ( self : Dict ): pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def _A ( self : Union[str, Any] ): pass def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): def check_hidden_states_output(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 16 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : str = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def _A ( self : Optional[Any] ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : int = MobileNetVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Optional[int] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ ) # verify the logits SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : int = model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.tensor( [ [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]], [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]], [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
62
1
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """kakaobrain/align-base""": """https://huggingface.co/kakaobrain/align-base/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : int = '''align_text_model''' def __init__( self : Dict , UpperCAmelCase_ : List[str]=3_0522 , UpperCAmelCase_ : Dict=768 , UpperCAmelCase_ : str=12 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : List[str]=3072 , UpperCAmelCase_ : Dict="gelu" , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : Optional[int]=1E-12 , UpperCAmelCase_ : List[str]=0 , UpperCAmelCase_ : List[Any]="absolute" , UpperCAmelCase_ : List[Any]=True , **UpperCAmelCase_ : Optional[int] , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = vocab_size SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : Dict = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : str = hidden_act SCREAMING_SNAKE_CASE : Dict = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = position_embedding_type SCREAMING_SNAKE_CASE : Optional[int] = use_cache SCREAMING_SNAKE_CASE : List[str] = pad_token_id @classmethod def _A ( cls : Any , UpperCAmelCase_ : Union[str, os.PathLike] , **UpperCAmelCase_ : Union[str, Any] ): cls._set_token_in_kwargs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = cls.get_config_dict(UpperCAmelCase_ , **UpperCAmelCase_ ) # get the text config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": SCREAMING_SNAKE_CASE : Optional[int] = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCAmelCase_ , **UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : int = '''align_vision_model''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 600 , UpperCAmelCase_ : float = 2.0 , UpperCAmelCase_ : float = 3.1 , UpperCAmelCase_ : int = 8 , UpperCAmelCase_ : List[int] = [3, 3, 5, 3, 5, 5, 3] , UpperCAmelCase_ : List[int] = [32, 16, 24, 40, 80, 112, 192] , UpperCAmelCase_ : List[int] = [16, 24, 40, 80, 112, 192, 320] , UpperCAmelCase_ : List[int] = [] , UpperCAmelCase_ : List[int] = [1, 2, 2, 2, 1, 2, 1] , UpperCAmelCase_ : List[int] = [1, 2, 2, 3, 3, 4, 1] , UpperCAmelCase_ : List[int] = [1, 6, 6, 6, 6, 6, 6] , UpperCAmelCase_ : float = 0.25 , UpperCAmelCase_ : str = "swish" , UpperCAmelCase_ : int = 2560 , UpperCAmelCase_ : str = "mean" , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : float = 0.001 , UpperCAmelCase_ : float = 0.99 , UpperCAmelCase_ : float = 0.2 , **UpperCAmelCase_ : List[str] , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = num_channels SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : List[Any] = width_coefficient SCREAMING_SNAKE_CASE : Union[str, Any] = depth_coefficient SCREAMING_SNAKE_CASE : List[Any] = depth_divisor SCREAMING_SNAKE_CASE : Tuple = kernel_sizes SCREAMING_SNAKE_CASE : int = in_channels SCREAMING_SNAKE_CASE : Union[str, Any] = out_channels SCREAMING_SNAKE_CASE : str = depthwise_padding SCREAMING_SNAKE_CASE : Dict = strides SCREAMING_SNAKE_CASE : List[str] = num_block_repeats SCREAMING_SNAKE_CASE : List[str] = expand_ratios SCREAMING_SNAKE_CASE : Union[str, Any] = squeeze_expansion_ratio SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : Any = hidden_dim SCREAMING_SNAKE_CASE : Dict = pooling_type SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Tuple = batch_norm_eps SCREAMING_SNAKE_CASE : int = batch_norm_momentum SCREAMING_SNAKE_CASE : Any = drop_connect_rate SCREAMING_SNAKE_CASE : Optional[Any] = sum(UpperCAmelCase_ ) * 4 @classmethod def _A ( cls : int , UpperCAmelCase_ : Union[str, os.PathLike] , **UpperCAmelCase_ : Union[str, Any] ): cls._set_token_in_kwargs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = cls.get_config_dict(UpperCAmelCase_ , **UpperCAmelCase_ ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": SCREAMING_SNAKE_CASE : List[Any] = 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 SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Dict = '''align''' UpperCamelCase_ : Optional[int] = True def __init__( self : str , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[int]=640 , UpperCAmelCase_ : List[Any]=1.0 , UpperCAmelCase_ : str=0.02 , **UpperCAmelCase_ : Optional[Any] , ): super().__init__(**UpperCAmelCase_ ) if text_config is None: SCREAMING_SNAKE_CASE : Union[str, Any] = {} logger.info("text_config is None. Initializing the AlignTextConfig with default values." ) if vision_config is None: SCREAMING_SNAKE_CASE : Tuple = {} logger.info("vision_config is None. Initializing the AlignVisionConfig with default values." ) SCREAMING_SNAKE_CASE : List[str] = AlignTextConfig(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = AlignVisionConfig(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = projection_dim SCREAMING_SNAKE_CASE : Tuple = temperature_init_value SCREAMING_SNAKE_CASE : str = initializer_range @classmethod def _A ( cls : Any , UpperCAmelCase_ : AlignTextConfig , UpperCAmelCase_ : AlignVisionConfig , **UpperCAmelCase_ : List[str] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCAmelCase_ ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Dict = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : List[str] = self.text_config.to_dict() SCREAMING_SNAKE_CASE : List[Any] = self.vision_config.to_dict() SCREAMING_SNAKE_CASE : str = self.__class__.model_type return output
62
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" def constraint_to_multiple_of(lowercase , lowercase , lowercase=0 , lowercase=None ): SCREAMING_SNAKE_CASE : Any = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : int = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Tuple = (output_size, output_size) if isinstance(lowercase , lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_image_size(lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Tuple = output_height / input_height SCREAMING_SNAKE_CASE : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width SCREAMING_SNAKE_CASE : List[str] = scale_width else: # fit height SCREAMING_SNAKE_CASE : Optional[Any] = scale_height SCREAMING_SNAKE_CASE : int = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase ) SCREAMING_SNAKE_CASE : Dict = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase ) return (new_height, new_width) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase_ : str , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = size if size is not None else {"height": 384, "width": 384} SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : int = ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample SCREAMING_SNAKE_CASE : List[str] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self : Tuple , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : int , ): SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = get_resize_output_image_size( UpperCAmelCase_ , output_size=(size["height"], size["width"]) , keep_aspect_ratio=UpperCAmelCase_ , multiple=UpperCAmelCase_ , ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Dict , ): return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ): return normalize(UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : Optional[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : List[str] = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Any = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Tuple = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Tuple = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Tuple] = None ): SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : str = [] for idx in range(len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
62
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = """▁""" snake_case = {"""vocab_file""": """sentencepiece.bpe.model"""} snake_case = { """vocab_file""": { """facebook/mbart-large-50-one-to-many-mmt""": ( """https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model""" ), } } snake_case = { """facebook/mbart-large-50-one-to-many-mmt""": 1_024, } # fmt: off snake_case = ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN""", """af_ZA""", """az_AZ""", """bn_IN""", """fa_IR""", """he_IL""", """hr_HR""", """id_ID""", """ka_GE""", """km_KH""", """mk_MK""", """ml_IN""", """mn_MN""", """mr_IN""", """pl_PL""", """ps_AF""", """pt_XX""", """sv_SE""", """sw_KE""", """ta_IN""", """te_IN""", """th_TH""", """tl_XX""", """uk_UA""", """ur_PK""", """xh_ZA""", """gl_ES""", """sl_SI"""] class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = VOCAB_FILES_NAMES UpperCamelCase_ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[Any] = ['''input_ids''', '''attention_mask'''] UpperCamelCase_ : List[int] = [] UpperCamelCase_ : List[int] = [] def __init__( self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Any="</s>" , UpperCAmelCase_ : Optional[int]="</s>" , UpperCAmelCase_ : str="<s>" , UpperCAmelCase_ : List[Any]="<unk>" , UpperCAmelCase_ : List[str]="<pad>" , UpperCAmelCase_ : Any="<mask>" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : List[str] , ): # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : Tuple = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE : Dict = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=UpperCAmelCase_ , tgt_lang=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : Optional[int] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE : Optional[int] = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE : Union[str, Any] = 1 SCREAMING_SNAKE_CASE : Any = len(self.sp_model ) SCREAMING_SNAKE_CASE : Union[str, Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(UpperCAmelCase_ ) } SCREAMING_SNAKE_CASE : List[str] = {v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE : str = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE : List[str] = src_lang if src_lang is not None else "en_XX" SCREAMING_SNAKE_CASE : Tuple = self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE : int = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _A ( self : Tuple ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _A ( self : List[Any] ): return self._src_lang @src_lang.setter def _A ( self : Optional[int] , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Optional[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Tuple ): SCREAMING_SNAKE_CASE : List[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE : Dict = None return state def __setstate__( self : List[Any] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : str = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE : List[Any] = {} SCREAMING_SNAKE_CASE : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _A ( self : Union[str, 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 _A ( self : List[str] , UpperCAmelCase_ : str ): return self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : str ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.PieceToId(UpperCAmelCase_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _A ( self : int , UpperCAmelCase_ : int ): 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 : List[str] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[Any] = "" SCREAMING_SNAKE_CASE : Optional[Any] = 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(UpperCAmelCase_ ) + token SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Optional[int] = [] else: current_sub_tokens.append(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def _A ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): if not os.path.isdir(UpperCAmelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : Union[str, 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_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , "wb" ) as fi: SCREAMING_SNAKE_CASE : List[str] = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,) def _A ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Optional[Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(UpperCAmelCase_ )) + suffix_ones return prefix_ones + ([0] * len(UpperCAmelCase_ )) + ([0] * len(UpperCAmelCase_ )) + suffix_ones def _A ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _A ( self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] , UpperCAmelCase_ : Optional[str] , **UpperCAmelCase_ : Any ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) SCREAMING_SNAKE_CASE : List[Any] = src_lang SCREAMING_SNAKE_CASE : str = self(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = tgt_lang_id return inputs def _A ( self : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str = "en_XX" , UpperCAmelCase_ : Optional[List[str]] = None , UpperCAmelCase_ : str = "ro_RO" , **UpperCAmelCase_ : Union[str, Any] , ): SCREAMING_SNAKE_CASE : Dict = src_lang SCREAMING_SNAKE_CASE : Dict = tgt_lang return super().prepare_seqaseq_batch(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] ): return self.set_src_lang_special_tokens(self.src_lang ) def _A ( self : Dict ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _A ( self : Any , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : List[Any] = self.lang_code_to_id[src_lang] SCREAMING_SNAKE_CASE : Dict = [self.cur_lang_code_id] SCREAMING_SNAKE_CASE : str = [self.eos_token_id] def _A ( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.lang_code_to_id[tgt_lang] SCREAMING_SNAKE_CASE : List[Any] = [self.cur_lang_code_id] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id]
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : int = 6 ): SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None self.create_linked_list(UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Optional[int] = Node() SCREAMING_SNAKE_CASE : str = current_node SCREAMING_SNAKE_CASE : Optional[int] = current_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node for _ in range(1 , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Tuple = Node() SCREAMING_SNAKE_CASE : Dict = current_node SCREAMING_SNAKE_CASE : Optional[Any] = previous_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node SCREAMING_SNAKE_CASE : Union[str, Any] = self.front SCREAMING_SNAKE_CASE : List[str] = previous_node def _A ( self : Union[str, Any] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _A ( self : Optional[int] ): self.check_can_perform_operation() return self.front.data if self.front else None def _A ( self : Optional[int] , UpperCAmelCase_ : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE : List[str] = self.rear.next if self.rear: SCREAMING_SNAKE_CASE : Dict = data def _A ( self : List[str] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE : List[str] = self.front.data SCREAMING_SNAKE_CASE : Optional[int] = None return data SCREAMING_SNAKE_CASE : List[str] = self.front SCREAMING_SNAKE_CASE : List[str] = old_front.next SCREAMING_SNAKE_CASE : Optional[int] = old_front.data SCREAMING_SNAKE_CASE : List[str] = None return data def _A ( self : Any ): if self.is_empty(): raise Exception("Empty Queue" ) def _A ( self : Optional[Any] ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any | None = None SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
62
1
import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any]=13 , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : int=99 , UpperCAmelCase_ : int=64 , UpperCAmelCase_ : Optional[int]=32 , UpperCAmelCase_ : Optional[int]=5 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Optional[int]=37 , UpperCAmelCase_ : Union[str, Any]="gelu" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Optional[Any]=512 , UpperCAmelCase_ : Optional[int]=16 , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : Optional[Any]=0.02 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=None , ): SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Any = batch_size SCREAMING_SNAKE_CASE : List[Any] = seq_length SCREAMING_SNAKE_CASE : Optional[Any] = is_training SCREAMING_SNAKE_CASE : Tuple = use_input_mask SCREAMING_SNAKE_CASE : List[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Any = use_labels SCREAMING_SNAKE_CASE : Tuple = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Dict = embedding_size SCREAMING_SNAKE_CASE : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Tuple = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : str = type_vocab_size SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : Dict = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = num_labels SCREAMING_SNAKE_CASE : List[str] = num_choices SCREAMING_SNAKE_CASE : Optional[int] = scope def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Any = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Any = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _A ( self : Union[str, Any] ): return MegatronBertConfig( 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 , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) def _A ( self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Any = MegatronBertModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = model(UpperCAmelCase_ ) 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 _A ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Optional[int] = MegatronBertForMaskedLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = MegatronBertForCausalLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Dict = MegatronBertForNextSentencePrediction(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def _A ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[Any] = MegatronBertForPreTraining(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , next_sentence_label=UpperCAmelCase_ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def _A ( self : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = MegatronBertForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Dict = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=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 : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : int = MegatronBertForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : int = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Any = MegatronBertForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : List[str] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : int = self.num_choices SCREAMING_SNAKE_CASE : Any = MegatronBertForMultipleChoice(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Any = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Optional[Any] = model( 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 : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE : str = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) UpperCamelCase_ : int = ( { '''feature-extraction''': MegatronBertModel, '''fill-mask''': MegatronBertForMaskedLM, '''question-answering''': MegatronBertForQuestionAnswering, '''text-classification''': MegatronBertForSequenceClassification, '''text-generation''': MegatronBertForCausalLM, '''token-classification''': MegatronBertForTokenClassification, '''zero-shot''': MegatronBertForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase_ : List[Any] = True # test_resize_embeddings = False UpperCamelCase_ : str = False def _A ( self : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : str=False ): SCREAMING_SNAKE_CASE : Any = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) if return_labels: if model_class in get_values(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_ ) return inputs_dict def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : int = MegatronBertModelTester(self ) SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def _A ( self : Any ): self.config_tester.run_common_tests() def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*UpperCAmelCase_ ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*UpperCAmelCase_ ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return torch.tensor( lowercase , dtype=torch.long , device=lowercase , ) snake_case = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow @unittest.skip("Model is not available." ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = "nvidia/megatron-bert-uncased-345m" if "MYDIR" in os.environ: SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(os.environ["MYDIR"] , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = MegatronBertModel.from_pretrained(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.half() SCREAMING_SNAKE_CASE : Dict = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Union[str, Any] = model(UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : str = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = [-0.6_040, -0.2_517, -0.1_025, 0.3_420, -0.6_758, -0.0_017, -0.1_089, -0.1_990, 0.5_728] for ii in range(3 ): for jj in range(3 ): SCREAMING_SNAKE_CASE : Optional[int] = output[0, ii, jj] SCREAMING_SNAKE_CASE : Tuple = expected[3 * ii + jj] SCREAMING_SNAKE_CASE : str = "ii={} jj={} a={} b={}".format(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertTrue(math.isclose(UpperCAmelCase_ , UpperCAmelCase_ , rel_tol=UpperCAmelCase_ , abs_tol=UpperCAmelCase_ ) , msg=UpperCAmelCase_ )
62
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
62
1
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return int(input_a == input_a == 0 ) def lowerCamelCase__ ( ): """simple docstring""" print("Truth Table of NOR Gate:" ) print("| Input 1 | Input 2 | Output |" ) print(F'''| 0 | 0 | {nor_gate(0 , 0 )} |''' ) print(F'''| 0 | 1 | {nor_gate(0 , 1 )} |''' ) print(F'''| 1 | 0 | {nor_gate(1 , 0 )} |''' ) print(F'''| 1 | 1 | {nor_gate(1 , 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
62
import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ ( lowercase , lowercase , lowercase = 1 , lowercase = 1 , lowercase = 1.0E4 , lowercase = False , lowercase = 1.0 , ): """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even''' SCREAMING_SNAKE_CASE : Union[str, Any] = float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE : Optional[Any] = min_timescale * jnp.exp(jnp.arange(lowercase , dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE : Optional[int] = jnp.expand_dims(lowercase , 1 ) * jnp.expand_dims(lowercase , 0 ) # scale embeddings SCREAMING_SNAKE_CASE : Optional[int] = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate([jnp.cos(lowercase ), jnp.sin(lowercase )] , axis=1 ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.concatenate([jnp.sin(lowercase ), jnp.cos(lowercase )] , axis=1 ) SCREAMING_SNAKE_CASE : Tuple = jnp.reshape(lowercase , [jnp.shape(lowercase )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.silu(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(UpperCAmelCase_ ) return temb class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : bool = False UpperCamelCase_ : float = 1 @nn.compact def __call__( self : Optional[int] , UpperCAmelCase_ : int ): return get_sinusoidal_embeddings( UpperCAmelCase_ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
62
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any]=13 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Dict=224 , UpperCAmelCase_ : Tuple=30 , UpperCAmelCase_ : Tuple=400 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase_ : str=[0.5, 0.5, 0.5] , ): SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : List[Any] = batch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : str = image_size SCREAMING_SNAKE_CASE : Tuple = min_resolution SCREAMING_SNAKE_CASE : int = max_resolution SCREAMING_SNAKE_CASE : Tuple = do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = size SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : List[str] = image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std def _A ( self : List[str] ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = ViTImageProcessor if is_vision_available() else None def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = EfficientFormerImageProcessorTester(self ) @property def _A ( self : Optional[Any] ): return self.image_proc_tester.prepare_image_processor_dict() def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , "image_mean" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "image_std" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_normalize" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "do_resize" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , "size" ) ) def _A ( self : Optional[Any] ): pass def _A ( self : List[str] ): # Initialize image_processor SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[str] = image_processor(UpperCAmelCase_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def _A ( self : Dict ): # Initialize image_processor SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Any = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Tuple = image_processor(UpperCAmelCase_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def _A ( self : Tuple ): # Initialize image_processor SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[str] = image_processor(UpperCAmelCase_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , )
62
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ : Any = '''image_segmenter''' UpperCamelCase_ : int = CLIPSegForImageSegmentation UpperCamelCase_ : Optional[Any] = ['''image''', '''text'''] UpperCamelCase_ : int = ['''image'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): with torch.no_grad(): SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits return logits def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
62
1
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = BertJapaneseTokenizer UpperCamelCase_ : Optional[Any] = False UpperCamelCase_ : str = True def _A ( self : Tuple ): super().setUp() SCREAMING_SNAKE_CASE : Dict = [ "[UNK]", "[CLS]", "[SEP]", "こんにちは", "こん", "にちは", "ばんは", "##こん", "##にちは", "##ばんは", "世界", "##世界", "、", "##、", "。", "##。", ] SCREAMING_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] ) ) def _A ( self : Tuple , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : List[str] = "こんにちは、世界。 \nこんばんは、世界。" SCREAMING_SNAKE_CASE : Tuple = "こんにちは 、 世界 。 こんばんは 、 世界 。" return input_text, output_text def _A ( self : List[Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.get_input_output_texts(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def _A ( self : List[Any] ): pass # TODO add if relevant def _A ( self : str ): pass # TODO add if relevant def _A ( self : Optional[Any] ): pass # TODO add if relevant def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize("こんにちは、世界。\nこんばんは、世界。" ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class(self.vocab_file , word_tokenizer_type="mecab" ) self.assertIsNotNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = "こんにちは、世界。\nこんばんは、世界。" SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , "tokenizer.bin" ) with open(UpperCAmelCase_ , "wb" ) as handle: pickle.dump(UpperCAmelCase_ , UpperCAmelCase_ ) with open(UpperCAmelCase_ , "rb" ) as handle: SCREAMING_SNAKE_CASE : List[Any] = pickle.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = tokenizer_new.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = MecabTokenizer(mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : Dict ): try: SCREAMING_SNAKE_CASE : List[Any] = MecabTokenizer(mecab_dic="unidic_lite" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : Dict ): try: SCREAMING_SNAKE_CASE : Optional[Any] = MecabTokenizer(mecab_dic="unidic" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Any = MecabTokenizer(do_lower_case=UpperCAmelCase_ , mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iphone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : List[str] ): try: SCREAMING_SNAKE_CASE : Tuple = MecabTokenizer( do_lower_case=UpperCAmelCase_ , normalize_text=UpperCAmelCase_ , mecab_option="-d /usr/local/lib/mecab/dic/jumandic" ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れた", "\u3000", "。"] , ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : List[Any] = MecabTokenizer(normalize_text=UpperCAmelCase_ , mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", " ", "。"] , ) @require_sudachi def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Any = self.tokenizer_class(self.vocab_file , word_tokenizer_type="sudachi" ) self.assertIsNotNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = "こんにちは、世界。\nこんばんは、世界。" SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Tuple = os.path.join(self.tmpdirname , "tokenizer.bin" ) with open(UpperCAmelCase_ , "wb" ) as handle: pickle.dump(UpperCAmelCase_ , UpperCAmelCase_ ) with open(UpperCAmelCase_ , "rb" ) as handle: SCREAMING_SNAKE_CASE : List[str] = pickle.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_new.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @require_sudachi def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : str = SudachiTokenizer(sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , [" ", "\t", "アップル", "ストア", "で", "iPhone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", " ", "。", " ", " "] , ) @require_sudachi def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = SudachiTokenizer(sudachi_dict_type="core" , sudachi_split_mode="A" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) , ["外国", "人", "参政", "権"] ) @require_sudachi def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = SudachiTokenizer(sudachi_dict_type="core" , sudachi_split_mode="B" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) , ["外国人", "参政権"] ) @require_sudachi def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = SudachiTokenizer(sudachi_dict_type="core" , sudachi_split_mode="C" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) , ["外国人参政権"] ) @require_sudachi def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Dict = SudachiTokenizer(do_lower_case=UpperCAmelCase_ , sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , [" ", "\t", "アップル", "ストア", "で", "iphone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", " ", "。", " ", " "] , ) @require_sudachi def _A ( self : Dict ): SCREAMING_SNAKE_CASE : int = SudachiTokenizer(normalize_text=UpperCAmelCase_ , sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , [" ", "\t", "アップル", "ストア", "で", "iPhone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", "\u3000", "。", " ", " "] , ) @require_sudachi def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = SudachiTokenizer(trim_whitespace=UpperCAmelCase_ , sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) @require_jumanpp def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.tokenizer_class(self.vocab_file , word_tokenizer_type="jumanpp" ) self.assertIsNotNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = "こんにちは、世界。\nこんばんは、世界。" SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , "tokenizer.bin" ) with open(UpperCAmelCase_ , "wb" ) as handle: pickle.dump(UpperCAmelCase_ , UpperCAmelCase_ ) with open(UpperCAmelCase_ , "rb" ) as handle: SCREAMING_SNAKE_CASE : List[Any] = pickle.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = tokenizer_new.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @require_jumanpp def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : str = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] , ) @require_jumanpp def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[Any] = JumanppTokenizer(do_lower_case=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iphone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] , ) @require_jumanpp def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : str = JumanppTokenizer(normalize_text=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["ア", "ッ", "フ", "゚", "ル", "ストア", "で", "iPhone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] , ) @require_jumanpp def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = JumanppTokenizer(trim_whitespace=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れた", "。"] , ) @require_jumanpp def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize("ありがとうございますm(_ _)m見つけるのが大変です。" ) , ["ありがとう", "ございます", "m(_ _)m", "見つける", "の", "が", "大変です", "。"] , ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = ["[UNK]", "[CLS]", "[SEP]", "こんにちは", "こん", "にちは", "ばんは", "##こん", "##にちは", "##ばんは"] SCREAMING_SNAKE_CASE : str = {} for i, token in enumerate(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = i SCREAMING_SNAKE_CASE : Optional[Any] = WordpieceTokenizer(vocab=UpperCAmelCase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("こんにちは" ) , ["こんにちは"] ) self.assertListEqual(tokenizer.tokenize("こんばんは" ) , ["こん", "##ばんは"] ) self.assertListEqual(tokenizer.tokenize("こんばんは こんばんにちは こんにちは" ) , ["こん", "##ばんは", "[UNK]", "こんにちは"] ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[Any] = BertJapaneseTokenizer.from_pretrained("nlp-waseda/roberta-base-japanese-with-auto-jumanpp" ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.subword_tokenizer SCREAMING_SNAKE_CASE : Any = subword_tokenizer.tokenize("国境 の 長い トンネル を 抜ける と 雪国 であった 。" ) self.assertListEqual(UpperCAmelCase_ , ["▁国境", "▁の", "▁長い", "▁トンネル", "▁を", "▁抜ける", "▁と", "▁雪", "国", "▁であった", "▁。"] ) SCREAMING_SNAKE_CASE : List[str] = subword_tokenizer.tokenize("こんばんは こんばん にち は こんにちは" ) self.assertListEqual(UpperCAmelCase_ , ["▁こん", "ばん", "は", "▁こん", "ばん", "▁に", "ち", "▁は", "▁こんにちは"] ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class.from_pretrained("cl-tohoku/bert-base-japanese" ) SCREAMING_SNAKE_CASE : Dict = tokenizer.encode("ありがとう。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode("どういたしまして。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ , UpperCAmelCase_ ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BertJapaneseTokenizer UpperCamelCase_ : Tuple = False def _A ( self : str ): super().setUp() SCREAMING_SNAKE_CASE : Tuple = ["[UNK]", "[CLS]", "[SEP]", "こ", "ん", "に", "ち", "は", "ば", "世", "界", "、", "。"] SCREAMING_SNAKE_CASE : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : str , **UpperCAmelCase_ : int ): return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type="character" , **UpperCAmelCase_ ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Tuple = "こんにちは、世界。 \nこんばんは、世界。" SCREAMING_SNAKE_CASE : Optional[Any] = "こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。" return input_text, output_text def _A ( self : Any ): pass # TODO add if relevant def _A ( self : Optional[int] ): pass # TODO add if relevant def _A ( self : Dict ): pass # TODO add if relevant def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Dict = self.tokenizer_class(self.vocab_file , subword_tokenizer_type="character" ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize("こんにちは、世界。 \nこんばんは、世界。" ) self.assertListEqual( UpperCAmelCase_ , ["こ", "ん", "に", "ち", "は", "、", "世", "界", "。", "こ", "ん", "ば", "ん", "は", "、", "世", "界", "。"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = ["[UNK]", "[CLS]", "[SEP]", "こ", "ん", "に", "ち", "は", "ば", "世", "界", "、", "。"] SCREAMING_SNAKE_CASE : Optional[int] = {} for i, token in enumerate(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = i SCREAMING_SNAKE_CASE : List[str] = CharacterTokenizer(vocab=UpperCAmelCase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("こんにちは" ) , ["こ", "ん", "に", "ち", "は"] ) self.assertListEqual(tokenizer.tokenize("こんにちほ" ) , ["こ", "ん", "に", "ち", "[UNK]"] ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Any = self.tokenizer_class.from_pretrained("cl-tohoku/bert-base-japanese-char" ) SCREAMING_SNAKE_CASE : str = tokenizer.encode("ありがとう。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.encode("どういたしまして。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ , UpperCAmelCase_ ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = "cl-tohoku/bert-base-japanese" SCREAMING_SNAKE_CASE : Any = AutoTokenizer.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : int ): SCREAMING_SNAKE_CASE : Any = "cl-tohoku/bert-base-japanese" with self.assertLogs("transformers" , level="WARNING" ) as cm: BertTokenizer.from_pretrained(UpperCAmelCase_ ) self.assertTrue( cm.records[0].message.startswith( "The tokenizer class you load from this checkpoint is not the same type as the class this function" " is called from." ) ) SCREAMING_SNAKE_CASE : Optional[Any] = "bert-base-cased" with self.assertLogs("transformers" , level="WARNING" ) as cm: BertJapaneseTokenizer.from_pretrained(UpperCAmelCase_ ) self.assertTrue( cm.records[0].message.startswith( "The tokenizer class you load from this checkpoint is not the same type as the class this function" " is called from." ) )
62
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 SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BlenderbotSmallTokenizer UpperCamelCase_ : int = False def _A ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] SCREAMING_SNAKE_CASE : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : List[Any] , **UpperCAmelCase_ : str ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : int = "adapt act apte" return input_text, output_text def _A ( self : str ): SCREAMING_SNAKE_CASE : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : List[str] = ["adapt", "act", "ap@@", "te"] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1384] SCREAMING_SNAKE_CASE : str = "I am a small frog." SCREAMING_SNAKE_CASE : List[Any] = tok([src_text] , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : int = tok.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) SCREAMING_SNAKE_CASE : Tuple = "I am a small frog ." SCREAMING_SNAKE_CASE : Optional[int] = "." SCREAMING_SNAKE_CASE : Dict = tok(UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : Optional[Any] = tok(UpperCAmelCase_ )["input_ids"] assert encoded[-1] == encoded_dot[0]
62
1
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) snake_case = """hf-internal-testing/tiny-random-bert""" snake_case = os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""") snake_case = """9b8c223d42b2188cb49d29af482996f9d0f3e5a6""" class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : str = cached_file(UpperCAmelCase_ , UpperCAmelCase_ ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(UpperCAmelCase_ ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) ) ) with open(os.path.join(UpperCAmelCase_ , "refs" , "main" ) ) as f: SCREAMING_SNAKE_CASE : List[Any] = f.read() self.assertEqual(UpperCAmelCase_ , os.path.join(UpperCAmelCase_ , "snapshots" , UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertTrue(os.path.isfile(UpperCAmelCase_ ) ) # File is cached at the same place the second time. SCREAMING_SNAKE_CASE : Tuple = cached_file(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ ) # Using a specific revision to test the full commit hash. SCREAMING_SNAKE_CASE : Tuple = cached_file(UpperCAmelCase_ , UpperCAmelCase_ , revision="9b8c223" ) self.assertEqual(UpperCAmelCase_ , os.path.join(UpperCAmelCase_ , "snapshots" , UpperCAmelCase_ , UpperCAmelCase_ ) ) def _A ( self : int ): with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid model identifier" ): SCREAMING_SNAKE_CASE : Tuple = cached_file("tiny-random-bert" , UpperCAmelCase_ ) with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid git identifier" ): SCREAMING_SNAKE_CASE : int = cached_file(UpperCAmelCase_ , UpperCAmelCase_ , revision="aaaa" ) with self.assertRaisesRegex(UpperCAmelCase_ , "does not appear to have a file named" ): SCREAMING_SNAKE_CASE : Optional[Any] = cached_file(UpperCAmelCase_ , "conf" ) def _A ( self : int ): with self.assertRaisesRegex(UpperCAmelCase_ , "does not appear to have a file named" ): SCREAMING_SNAKE_CASE : Any = cached_file(UpperCAmelCase_ , "conf" ) with open(os.path.join(UpperCAmelCase_ , "refs" , "main" ) ) as f: SCREAMING_SNAKE_CASE : int = f.read() self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase_ , ".no_exist" , UpperCAmelCase_ , "conf" ) ) ) SCREAMING_SNAKE_CASE : str = cached_file(UpperCAmelCase_ , "conf" , _raise_exceptions_for_missing_entries=UpperCAmelCase_ ) self.assertIsNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = cached_file(UpperCAmelCase_ , "conf" , local_files_only=UpperCAmelCase_ , _raise_exceptions_for_missing_entries=UpperCAmelCase_ ) self.assertIsNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = mock.Mock() SCREAMING_SNAKE_CASE : Optional[Any] = 500 SCREAMING_SNAKE_CASE : Optional[int] = {} SCREAMING_SNAKE_CASE : Dict = HTTPError SCREAMING_SNAKE_CASE : Union[str, Any] = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=UpperCAmelCase_ ) as mock_head: SCREAMING_SNAKE_CASE : Tuple = cached_file(UpperCAmelCase_ , "conf" , _raise_exceptions_for_connection_errors=UpperCAmelCase_ ) self.assertIsNone(UpperCAmelCase_ ) # This check we did call the fake head request mock_head.assert_called() def _A ( self : List[Any] ): self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase_ ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase_ ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase_ ) ) def _A ( self : str ): # `get_file_from_repo` returns None if the file does not exist self.assertIsNone(get_file_from_repo("bert-base-cased" , "ahah.txt" ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid model identifier" ): get_file_from_repo("bert-base-case" , UpperCAmelCase_ ) # The function raises if the revision does not exist. with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid git identifier" ): get_file_from_repo("bert-base-cased" , UpperCAmelCase_ , revision="ahaha" ) SCREAMING_SNAKE_CASE : Tuple = get_file_from_repo("bert-base-cased" , UpperCAmelCase_ ) # The name is the cached name which is not very easy to test, so instead we load the content. SCREAMING_SNAKE_CASE : List[str] = json.loads(open(UpperCAmelCase_ , "r" ).read() ) self.assertEqual(config["hidden_size"] , 768 ) def _A ( self : Dict ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Union[str, Any] = Path(UpperCAmelCase_ ) / "a.txt" filename.touch() self.assertEqual(get_file_from_repo(UpperCAmelCase_ , "a.txt" ) , str(UpperCAmelCase_ ) ) self.assertIsNone(get_file_from_repo(UpperCAmelCase_ , "b.txt" ) )
62
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] snake_case = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = torch.load(lowercase , map_location="cpu" ) return sd def lowerCamelCase__ ( lowercase , lowercase , lowercase=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE : Union[str, Any] = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE : Any = new_key.replace(name_pair[0] , name_pair[1] ) SCREAMING_SNAKE_CASE : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE : Union[str, Any] = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = "pretraining" if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Any = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 512} SCREAMING_SNAKE_CASE : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = {"visual_embedding_dim": 2048} SCREAMING_SNAKE_CASE : str = "vqa_advanced" elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Tuple = {"visual_embedding_dim": 2048, "num_labels": 3129} SCREAMING_SNAKE_CASE : Optional[Any] = "vqa" elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = { "visual_embedding_dim": 1024, "num_labels": 2, } SCREAMING_SNAKE_CASE : Tuple = "nlvr" SCREAMING_SNAKE_CASE : List[Any] = VisualBertConfig(**lowercase ) # Load State Dict SCREAMING_SNAKE_CASE : List[str] = load_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Any = get_new_dict(lowercase , lowercase ) if model_type == "pretraining": SCREAMING_SNAKE_CASE : int = VisualBertForPreTraining(lowercase ) elif model_type == "vqa": SCREAMING_SNAKE_CASE : Tuple = VisualBertForQuestionAnswering(lowercase ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE : List[Any] = VisualBertForVisualReasoning(lowercase ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE : Optional[Any] = VisualBertForMultipleChoice(lowercase ) model.load_state_dict(lowercase ) # Save Checkpoints Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
62
1
import itertools import string from collections.abc import Generator, Iterable def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = iter(lowercase ) while True: SCREAMING_SNAKE_CASE : int = tuple(itertools.islice(lowercase , lowercase ) ) if not chunk: return yield chunk def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = "".join([c.upper() for c in dirty if c in string.ascii_letters] ) SCREAMING_SNAKE_CASE : int = "" if len(lowercase ) < 2: return dirty for i in range(len(lowercase ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(lowercase ) & 1: clean += "X" return clean def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler SCREAMING_SNAKE_CASE : Dict = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(lowercase ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(lowercase ) return table def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = generate_table(lowercase ) SCREAMING_SNAKE_CASE : int = prepare_input(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(lowercase , 2 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = divmod(table.index(lowercase ) , 5 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = divmod(table.index(lowercase ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = generate_table(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(lowercase , 2 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = divmod(table.index(lowercase ) , 5 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = divmod(table.index(lowercase ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """JukeboxPriorConfig""", """JukeboxVQVAEConfig""", ], """tokenization_jukebox""": ["""JukeboxTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """JukeboxModel""", """JukeboxPreTrainedModel""", """JukeboxVQVAE""", """JukeboxPrior""", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
1
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor snake_case = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCamelCase__ ( lowercase ): """simple docstring""" if isinstance(lowercase , torch.Tensor ): return image elif isinstance(lowercase , PIL.Image.Image ): SCREAMING_SNAKE_CASE : Dict = [image] SCREAMING_SNAKE_CASE : Tuple = [trans(img.convert("RGB" ) ) for img in image] SCREAMING_SNAKE_CASE : Dict = torch.stack(lowercase ) return image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple ): super().__init__() # make sure scheduler can always be converted to DDIM SCREAMING_SNAKE_CASE : Dict = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ ) def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] ): if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any ): # get the original timestep using init_timestep SCREAMING_SNAKE_CASE : str = min(int(num_inference_steps * strength ) , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = max(num_inference_steps - init_timestep , 0 ) SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _A ( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any]=None ): if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_ )}''' ) SCREAMING_SNAKE_CASE : str = image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and len(UpperCAmelCase_ ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(UpperCAmelCase_ )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE : Optional[Any] = init_latents.shape SCREAMING_SNAKE_CASE : Any = randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_ ) # get latents print("add noise to latents at timestep" , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = init_latents return latents @torch.no_grad() def __call__( self : List[str] , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ): self.check_inputs(UpperCAmelCase_ ) # 2. Preprocess image SCREAMING_SNAKE_CASE : Optional[int] = preprocess(UpperCAmelCase_ ) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device ) SCREAMING_SNAKE_CASE : Tuple = timesteps[:1].repeat(UpperCAmelCase_ ) # 4. Prepare latent variables SCREAMING_SNAKE_CASE : List[Any] = self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_ ): # 1. predict noise model_output SCREAMING_SNAKE_CASE : Optional[int] = self.unet(UpperCAmelCase_ , UpperCAmelCase_ ).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 SCREAMING_SNAKE_CASE : Dict = self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample SCREAMING_SNAKE_CASE : Tuple = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : List[str] = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_ )
62
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ snake_case = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ snake_case = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _A ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def _A ( self : List[Any] , UpperCAmelCase_ : List[List[List[str]]] , UpperCAmelCase_ : List[List[str]] , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCAmelCase_ , hypotheses=UpperCAmelCase_ , min_len=UpperCAmelCase_ , max_len=UpperCAmelCase_ ) }
62
1
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 lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png" SCREAMING_SNAKE_CASE : Any = Image.open(requests.get(lowercase , stream=lowercase ).raw ).convert("RGB" ) return image def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = [] # 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 lowerCamelCase__ ( lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = dct.pop(lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = val def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) SCREAMING_SNAKE_CASE : Any = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict SCREAMING_SNAKE_CASE : Optional[int] = torch.cat((q_bias, torch.zeros_like(lowercase , requires_grad=lowercase ), v_bias) ) SCREAMING_SNAKE_CASE : Dict = qkv_bias def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 364 if "coco" in model_name else 224 SCREAMING_SNAKE_CASE : Union[str, Any] = BlipaVisionConfig(image_size=lowercase ).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: SCREAMING_SNAKE_CASE : Dict = OPTConfig.from_pretrained("facebook/opt-2.7b" , eos_token_id=lowercase ).to_dict() elif "opt-6.7b" in model_name: SCREAMING_SNAKE_CASE : int = OPTConfig.from_pretrained("facebook/opt-6.7b" , eos_token_id=lowercase ).to_dict() elif "t5-xl" in model_name: SCREAMING_SNAKE_CASE : Optional[Any] = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: SCREAMING_SNAKE_CASE : Optional[int] = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() SCREAMING_SNAKE_CASE : Tuple = BlipaConfig(vision_config=lowercase , text_config=lowercase ) return config, image_size @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase=None , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = ( AutoTokenizer.from_pretrained("facebook/opt-2.7b" ) if "opt" in model_name else AutoTokenizer.from_pretrained("google/flan-t5-xl" ) ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer("\n" , add_special_tokens=lowercase ).input_ids[0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = get_blipa_config(lowercase , eos_token_id=lowercase ) SCREAMING_SNAKE_CASE : int = BlipaForConditionalGeneration(lowercase ).eval() SCREAMING_SNAKE_CASE : Optional[Any] = { "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"), } SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = model_name_to_original[model_name] # load original model print("Loading original model..." ) SCREAMING_SNAKE_CASE : Tuple = "cuda" if torch.cuda.is_available() else "cpu" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = load_model_and_preprocess( name=lowercase , model_type=lowercase , is_eval=lowercase , device=lowercase ) original_model.eval() print("Done!" ) # update state dict keys SCREAMING_SNAKE_CASE : Tuple = original_model.state_dict() SCREAMING_SNAKE_CASE : int = create_rename_keys(lowercase ) for src, dest in rename_keys: rename_key(lowercase , lowercase , lowercase ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(lowercase ) if key.startswith("Qformer.bert" ): SCREAMING_SNAKE_CASE : Any = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: SCREAMING_SNAKE_CASE : Dict = key.replace("self" , "attention" ) if "opt_proj" in key: SCREAMING_SNAKE_CASE : Dict = key.replace("opt_proj" , "language_projection" ) if "t5_proj" in key: SCREAMING_SNAKE_CASE : int = key.replace("t5_proj" , "language_projection" ) if key.startswith("opt" ): SCREAMING_SNAKE_CASE : Optional[int] = key.replace("opt" , "language" ) if key.startswith("t5" ): SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace("t5" , "language" ) SCREAMING_SNAKE_CASE : Optional[Any] = val # read in qv biases read_in_q_v_bias(lowercase , lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = hf_model.load_state_dict(lowercase , strict=lowercase ) assert len(lowercase ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] SCREAMING_SNAKE_CASE : Dict = load_demo_image() SCREAMING_SNAKE_CASE : str = vis_processors["eval"](lowercase ).unsqueeze(0 ).to(lowercase ) SCREAMING_SNAKE_CASE : int = tokenizer(["\n"] , return_tensors="pt" ).input_ids.to(lowercase ) # create processor SCREAMING_SNAKE_CASE : List[Any] = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=lowercase , image_std=lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = BlipaProcessor(image_processor=lowercase , tokenizer=lowercase ) SCREAMING_SNAKE_CASE : Dict = processor(images=lowercase , return_tensors="pt" ).pixel_values.to(lowercase ) # make sure processor creates exact same pixel values assert torch.allclose(lowercase , lowercase ) original_model.to(lowercase ) hf_model.to(lowercase ) with torch.no_grad(): if "opt" in model_name: SCREAMING_SNAKE_CASE : List[str] = original_model({"image": original_pixel_values, "text_input": [""]} ).logits SCREAMING_SNAKE_CASE : int = hf_model(lowercase , lowercase ).logits else: SCREAMING_SNAKE_CASE : Dict = original_model( {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]} ).logits SCREAMING_SNAKE_CASE : List[Any] = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) SCREAMING_SNAKE_CASE : Any = hf_model(lowercase , lowercase , labels=lowercase ).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": SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=lowercase ) assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": SCREAMING_SNAKE_CASE : Dict = torch.tensor( [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=lowercase ) else: # cast to same type SCREAMING_SNAKE_CASE : Tuple = logits.dtype assert torch.allclose(original_logits.to(lowercase ) , lowercase , atol=1E-2 ) print("Looks ok!" ) print("Generating a caption..." ) SCREAMING_SNAKE_CASE : str = "" SCREAMING_SNAKE_CASE : int = tokenizer(lowercase , return_tensors="pt" ).input_ids.to(lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = original_model.generate({"image": original_pixel_values} ) SCREAMING_SNAKE_CASE : List[str] = hf_model.generate( lowercase , lowercase , do_sample=lowercase , 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:" , lowercase ) SCREAMING_SNAKE_CASE : List[str] = input_ids.shape[1] SCREAMING_SNAKE_CASE : Dict = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=lowercase ) SCREAMING_SNAKE_CASE : Any = [text.strip() for text in output_text] print("HF generation:" , lowercase ) if pytorch_dump_folder_path is not None: processor.save_pretrained(lowercase ) hf_model.save_pretrained(lowercase ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() snake_case = [ """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""", ) snake_case = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = row, column SCREAMING_SNAKE_CASE : Optional[Any] = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE : Optional[Any] = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = f'''%{max_element_length}s''' # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE : Optional[int] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Dict ): return str(self ) def _A ( self : Optional[int] , UpperCAmelCase_ : tuple[int, int] ): if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase_ : tuple[int, int] ): assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : int , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ): assert self.validate_indicies(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : Any = self[r, c] + another[r, c] return result def __neg__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ): return self + (-another) def __mul__( self : Dict , UpperCAmelCase_ : int | float | Matrix ): if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE : Any = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE : List[str] = f'''Unsupported type given for another ({type(UpperCAmelCase_ )})''' raise TypeError(UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : List[str] = self[r, c] return result def _A ( self : Union[str, Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE : Tuple = v.transpose() SCREAMING_SNAKE_CASE : int = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE : str = 1 print(F'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE : Optional[int] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 2, -3 SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase , lowercase )}''' ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() testa()
62
1
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any]=14 , UpperCAmelCase_ : Optional[Any]=7 , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : str=True , UpperCAmelCase_ : str=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[str]=4 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : Dict="gelu" , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : int=512 , UpperCAmelCase_ : int=0.02 , ): SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Tuple = batch_size SCREAMING_SNAKE_CASE : List[str] = seq_length SCREAMING_SNAKE_CASE : List[Any] = is_training SCREAMING_SNAKE_CASE : Any = use_input_mask SCREAMING_SNAKE_CASE : int = use_token_type_ids SCREAMING_SNAKE_CASE : Any = use_labels SCREAMING_SNAKE_CASE : str = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : str = rotary_dim SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : Tuple = intermediate_size SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : int = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Optional[int] = vocab_size - 1 SCREAMING_SNAKE_CASE : Tuple = vocab_size - 1 SCREAMING_SNAKE_CASE : str = vocab_size - 1 def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Tuple = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCAmelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def _A ( self : str ): SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE : List[Any] = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Union[str, Any] = 20 SCREAMING_SNAKE_CASE : Optional[Any] = model_class_name(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="i4" ) SCREAMING_SNAKE_CASE : int = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE : str = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : int = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4" ) SCREAMING_SNAKE_CASE : List[str] = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) def _A ( self : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : Any = 20 SCREAMING_SNAKE_CASE : Tuple = model_class_name(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) SCREAMING_SNAKE_CASE : Optional[Any] = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE : Any = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : int = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4" ) SCREAMING_SNAKE_CASE : Optional[int] = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) @require_flax class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () UpperCamelCase_ : List[Any] = (FlaxGPTJForCausalLM,) if is_flax_available() else () def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = FlaxGPTJModelTester(self ) def _A ( self : Optional[Any] ): for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : int ): for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @tooslow def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Tuple = GPTaTokenizer.from_pretrained("gpt2" , pad_token="<|endoftext|>" , padding_side="left" ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(["Hello this is a long string", "Hey"] , return_tensors="np" , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B" ) SCREAMING_SNAKE_CASE : str = False SCREAMING_SNAKE_CASE : Optional[Any] = model.config.eos_token_id SCREAMING_SNAKE_CASE : Any = jax.jit(model.generate ) SCREAMING_SNAKE_CASE : Optional[int] = jit_generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , pad_token_id=tokenizer.pad_token_id ).sequences SCREAMING_SNAKE_CASE : Dict = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = [ "Hello this is a long string of text.\n\nI'm trying to get the text of the", "Hey, I'm a little late to the party. I'm going to", ] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @is_pt_flax_cross_test def _A ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE : Optional[int] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE : Any = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = pt_inputs["input_ids"].shape SCREAMING_SNAKE_CASE : Optional[Any] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Any = 0 SCREAMING_SNAKE_CASE : str = 1 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : List[str] = 1 SCREAMING_SNAKE_CASE : int = pt_model_class(UpperCAmelCase_ ).eval() SCREAMING_SNAKE_CASE : Dict = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE : List[str] = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = fx_state with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = pt_model(**UpperCAmelCase_ ).to_tuple() SCREAMING_SNAKE_CASE : Tuple = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = model_class.from_pretrained(UpperCAmelCase_ , from_pt=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = fx_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output_loaded, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def _A ( self : Dict ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE : Optional[int] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE : List[str] = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = pt_model_class(UpperCAmelCase_ ).eval() SCREAMING_SNAKE_CASE : str = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE : int = load_flax_weights_in_pytorch_model(UpperCAmelCase_ , fx_model.params ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = pt_inputs["input_ids"].shape SCREAMING_SNAKE_CASE : Optional[int] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Tuple = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): SCREAMING_SNAKE_CASE : Union[str, Any] = pt_model(**UpperCAmelCase_ ).to_tuple() SCREAMING_SNAKE_CASE : Dict = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = pt_model_class.from_pretrained(UpperCAmelCase_ , from_flax=UpperCAmelCase_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE : int = pt_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def _A ( self : Optional[Any] ): for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = model_class_name.from_pretrained("EleutherAI/gpt-j-6B" ) SCREAMING_SNAKE_CASE : Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ )
62
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } snake_case = { """junnyu/roformer_chinese_small""": 1_536, """junnyu/roformer_chinese_base""": 1_536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } snake_case = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = RoFormerTokenizer def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : List[str]="[UNK]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : Any="[PAD]" , UpperCAmelCase_ : List[str]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : List[str] , ): 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_ , ) SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase_ ) != strip_accents ): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : List[str] = strip_accents SCREAMING_SNAKE_CASE : Tuple = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : Tuple , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = d SCREAMING_SNAKE_CASE : Dict = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE : Any = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase_ ) ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _A ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : List[Any] = [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 _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Optional[int] = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
62
1
import comet # From: unbabel-comet import torch import datasets snake_case = datasets.logging.get_logger(__name__) snake_case = """\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel's Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = \"{COMET}: A Neural Framework for {MT} Evaluation\", author = \"Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon\", booktitle = \"Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)\", month = nov, year = \"2020\", address = \"Online\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/2020.emnlp-main.213\", pages = \"2685--2702\", } """ snake_case = """\ Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA's or MQM). With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. """ snake_case = """ COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric('comet') >>> # comet_metric = load_metric('comet', 'wmt20-comet-da') # you can also choose which model to use >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"] >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"] >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results[\"scores\"]]) [0.19, 0.92] """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _A ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://unbabel.github.io/COMET/html/index.html" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "sources": datasets.Value("string" , id="sequence" ), "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/Unbabel/COMET"] , reference_urls=[ "https://github.com/Unbabel/COMET", "https://www.aclweb.org/anthology/2020.emnlp-main.213/", "http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6", ] , ) def _A ( self : List[Any] , UpperCAmelCase_ : List[Any] ): if self.config_name == "default": SCREAMING_SNAKE_CASE : int = comet.load_from_checkpoint(comet.download_model("wmt20-comet-da" ) ) else: SCREAMING_SNAKE_CASE : Tuple = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def _A ( self : Dict , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[int]=False ): if gpus is None: SCREAMING_SNAKE_CASE : List[Any] = 1 if torch.cuda.is_available() else 0 SCREAMING_SNAKE_CASE : int = {"src": sources, "mt": predictions, "ref": references} SCREAMING_SNAKE_CASE : str = [dict(zip(UpperCAmelCase_ , UpperCAmelCase_ ) ) for t in zip(*data.values() )] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.scorer.predict(UpperCAmelCase_ , gpus=UpperCAmelCase_ , progress_bar=UpperCAmelCase_ ) return {"mean_score": mean_score, "scores": scores}
62
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE : Optional[int] = str(abs(lowercase ) ) SCREAMING_SNAKE_CASE : str = [list(lowercase ) for char in range(len(lowercase ) )] for index in range(len(lowercase ) ): num_transpositions[index].pop(lowercase ) return max( int("".join(list(lowercase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
62
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = AudioLDMPipeline UpperCamelCase_ : Dict = TEXT_TO_AUDIO_PARAMS UpperCamelCase_ : Dict = TEXT_TO_AUDIO_BATCH_PARAMS UpperCamelCase_ : Union[str, Any] = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _A ( self : Tuple ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = 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, 64) , class_embed_type="simple_projection" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : List[str] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = ClapTextConfig( 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 , projection_dim=32 , ) SCREAMING_SNAKE_CASE : Dict = ClapTextModelWithProjection(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta" , model_max_length=77 ) SCREAMING_SNAKE_CASE : Union[str, Any] = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : int = SpeechTaHifiGan(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "vocoder": vocoder, } return components def _A ( self : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int]=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : str = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A hammer hitting a wooden surface", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, } return inputs def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Tuple = AudioLDMPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = audioldm_pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = output.audios[0] assert audio.ndim == 1 assert len(UpperCAmelCase_ ) == 256 SCREAMING_SNAKE_CASE : str = audio[:10] SCREAMING_SNAKE_CASE : List[Any] = np.array( [-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = AudioLDMPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = audioldm_pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = 3 * [inputs["prompt"]] # forward SCREAMING_SNAKE_CASE : List[Any] = audioldm_pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = output.audios[0] SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 3 * [inputs.pop("prompt" )] SCREAMING_SNAKE_CASE : List[str] = audioldm_pipe.tokenizer( UpperCAmelCase_ , padding="max_length" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=UpperCAmelCase_ , return_tensors="pt" , ) SCREAMING_SNAKE_CASE : Union[str, Any] = text_inputs["input_ids"].to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = audioldm_pipe.text_encoder( UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state SCREAMING_SNAKE_CASE : List[Any] = F.normalize(UpperCAmelCase_ , dim=-1 ) SCREAMING_SNAKE_CASE : Optional[Any] = prompt_embeds # forward SCREAMING_SNAKE_CASE : Any = audioldm_pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : str = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = AudioLDMPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = audioldm_pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = 3 * ["this is a negative prompt"] SCREAMING_SNAKE_CASE : Optional[Any] = negative_prompt SCREAMING_SNAKE_CASE : str = 3 * [inputs["prompt"]] # forward SCREAMING_SNAKE_CASE : Dict = audioldm_pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = output.audios[0] SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 3 * [inputs.pop("prompt" )] SCREAMING_SNAKE_CASE : Any = [] for p in [prompt, negative_prompt]: SCREAMING_SNAKE_CASE : Any = audioldm_pipe.tokenizer( UpperCAmelCase_ , padding="max_length" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=UpperCAmelCase_ , return_tensors="pt" , ) SCREAMING_SNAKE_CASE : Dict = text_inputs["input_ids"].to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = audioldm_pipe.text_encoder( UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = text_embeds.text_embeds # additional L_2 normalization over each hidden-state SCREAMING_SNAKE_CASE : Optional[int] = F.normalize(UpperCAmelCase_ , dim=-1 ) embeds.append(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = embeds # forward SCREAMING_SNAKE_CASE : Dict = audioldm_pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[int] = PNDMScheduler(skip_prk_steps=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = AudioLDMPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = "egg cracking" SCREAMING_SNAKE_CASE : int = audioldm_pipe(**UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = output.audios[0] assert audio.ndim == 1 assert len(UpperCAmelCase_ ) == 256 SCREAMING_SNAKE_CASE : Union[str, Any] = audio[:10] SCREAMING_SNAKE_CASE : Optional[Any] = np.array( [-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : int = PNDMScheduler(skip_prk_steps=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = AudioLDMPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = "A hammer hitting a wooden surface" # test num_waveforms_per_prompt=1 (default) SCREAMING_SNAKE_CASE : str = audioldm_pipe(UpperCAmelCase_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Optional[Any] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt SCREAMING_SNAKE_CASE : Dict = 2 SCREAMING_SNAKE_CASE : Any = audioldm_pipe(UpperCAmelCase_ , num_inference_steps=2 , num_waveforms_per_prompt=UpperCAmelCase_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts SCREAMING_SNAKE_CASE : List[str] = 2 SCREAMING_SNAKE_CASE : Tuple = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=UpperCAmelCase_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Union[str, Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = AudioLDMPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = audioldm_pipe.vocoder.config.sampling_rate SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = audioldm_pipe(audio_length_in_s=0.016 , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = output.audios[0] assert audio.ndim == 1 assert len(UpperCAmelCase_ ) / vocoder_sampling_rate == 0.016 SCREAMING_SNAKE_CASE : Optional[int] = audioldm_pipe(audio_length_in_s=0.032 , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = output.audios[0] assert audio.ndim == 1 assert len(UpperCAmelCase_ ) / vocoder_sampling_rate == 0.032 def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Union[str, Any] = AudioLDMPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = ["hey"] SCREAMING_SNAKE_CASE : Optional[Any] = audioldm_pipe(UpperCAmelCase_ , num_inference_steps=1 ) SCREAMING_SNAKE_CASE : Optional[int] = output.audios.shape assert audio_shape == (1, 256) SCREAMING_SNAKE_CASE : Tuple = audioldm_pipe.vocoder.config config.model_in_dim *= 2 SCREAMING_SNAKE_CASE : List[Any] = SpeechTaHifiGan(UpperCAmelCase_ ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = audioldm_pipe(UpperCAmelCase_ , num_inference_steps=1 ) SCREAMING_SNAKE_CASE : List[Any] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def _A ( self : Union[str, Any] ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=UpperCAmelCase_ ) def _A ( self : Any ): self._test_inference_batch_single_identical(test_mean_pixel_difference=UpperCAmelCase_ ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _A ( self : int ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCAmelCase_ ) @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Union[str, Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int="cpu" , UpperCAmelCase_ : Optional[int]=torch.floataa , UpperCAmelCase_ : Optional[Any]=0 ): SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = np.random.RandomState(UpperCAmelCase_ ).standard_normal((1, 8, 128, 16) ) SCREAMING_SNAKE_CASE : List[str] = torch.from_numpy(UpperCAmelCase_ ).to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = { "prompt": "A hammer hitting a wooden surface", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 2.5, } return inputs def _A ( self : str ): SCREAMING_SNAKE_CASE : List[Any] = AudioLDMPipeline.from_pretrained("cvssp/audioldm" ) SCREAMING_SNAKE_CASE : Optional[int] = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.get_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = 25 SCREAMING_SNAKE_CASE : Dict = audioldm_pipe(**UpperCAmelCase_ ).audios[0] assert audio.ndim == 1 assert len(UpperCAmelCase_ ) == 8_1920 SCREAMING_SNAKE_CASE : str = audio[7_7230:7_7240] SCREAMING_SNAKE_CASE : Dict = np.array( [-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315] ) SCREAMING_SNAKE_CASE : int = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1E-2 def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : str = AudioLDMPipeline.from_pretrained("cvssp/audioldm" ) SCREAMING_SNAKE_CASE : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) SCREAMING_SNAKE_CASE : Optional[int] = audioldm_pipe.to(UpperCAmelCase_ ) audioldm_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.get_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = audioldm_pipe(**UpperCAmelCase_ ).audios[0] assert audio.ndim == 1 assert len(UpperCAmelCase_ ) == 8_1920 SCREAMING_SNAKE_CASE : List[Any] = audio[2_7780:2_7790] SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212] ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3E-2
62
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = 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 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : int ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) 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 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _A ( self : Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-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 : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9E-2
62
1
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[int] = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 5_0257 , UpperCAmelCase_ : int = 1024 , UpperCAmelCase_ : int = 768 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = "gelu_new" , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 1E-5 , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , ): super().__init__() SCREAMING_SNAKE_CASE : Tuple = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and''' f''' `n_embd`: {n_embd} are not equal.''' ) SCREAMING_SNAKE_CASE : Optional[int] = prefix_inner_dim SCREAMING_SNAKE_CASE : Optional[int] = prefix_hidden_dim SCREAMING_SNAKE_CASE : Dict = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE : List[Any] = ( nn.Linear(self.prefix_hidden_dim , UpperCAmelCase_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE : Optional[int] = GPTaConfig( vocab_size=UpperCAmelCase_ , n_positions=UpperCAmelCase_ , n_embd=UpperCAmelCase_ , n_layer=UpperCAmelCase_ , n_head=UpperCAmelCase_ , n_inner=UpperCAmelCase_ , activation_function=UpperCAmelCase_ , resid_pdrop=UpperCAmelCase_ , embd_pdrop=UpperCAmelCase_ , attn_pdrop=UpperCAmelCase_ , layer_norm_epsilon=UpperCAmelCase_ , initializer_range=UpperCAmelCase_ , scale_attn_weights=UpperCAmelCase_ , use_cache=UpperCAmelCase_ , scale_attn_by_inverse_layer_idx=UpperCAmelCase_ , reorder_and_upcast_attn=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = GPTaLMHeadModel(UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : torch.Tensor , UpperCAmelCase_ : torch.Tensor , UpperCAmelCase_ : Optional[torch.Tensor] = None , UpperCAmelCase_ : Optional[torch.Tensor] = None , ): SCREAMING_SNAKE_CASE : List[str] = self.transformer.transformer.wte(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = self.encode_prefix(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.decode_prefix(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: SCREAMING_SNAKE_CASE : Any = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) SCREAMING_SNAKE_CASE : Any = torch.cat((dummy_token, input_ids) , dim=1 ) SCREAMING_SNAKE_CASE : Optional[Any] = self.transformer(inputs_embeds=UpperCAmelCase_ , labels=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _A ( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : torch.device ): return torch.zeros(UpperCAmelCase_ , self.prefix_length , dtype=torch.intaa , device=UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ): return self.encode_prefix(UpperCAmelCase_ ) @torch.no_grad() def _A ( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = torch.split(UpperCAmelCase_ , 1 , dim=0 ) SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Dict = [] for feature in features: SCREAMING_SNAKE_CASE : List[Any] = self.decode_prefix(feature.to(UpperCAmelCase_ ) ) # back to the clip feature # Only support beam search for now SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.generate_beam( input_embeds=UpperCAmelCase_ , device=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) SCREAMING_SNAKE_CASE : int = torch.stack(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = torch.stack(UpperCAmelCase_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _A ( self : Any , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int = 5 , UpperCAmelCase_ : int = 67 , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : Optional[int] = None , ): SCREAMING_SNAKE_CASE : Tuple = eos_token_id SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : str = torch.ones(UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=torch.int ) SCREAMING_SNAKE_CASE : Any = torch.zeros(UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=torch.bool ) if input_embeds is not None: SCREAMING_SNAKE_CASE : Tuple = input_embeds else: SCREAMING_SNAKE_CASE : int = self.transformer.transformer.wte(UpperCAmelCase_ ) for i in range(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.transformer(inputs_embeds=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = outputs.logits SCREAMING_SNAKE_CASE : int = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) SCREAMING_SNAKE_CASE : Dict = logits.softmax(-1 ).log() if scores is None: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = logits.topk(UpperCAmelCase_ , -1 ) SCREAMING_SNAKE_CASE : Tuple = generated.expand(UpperCAmelCase_ , *generated.shape[1:] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: SCREAMING_SNAKE_CASE : str = next_tokens else: SCREAMING_SNAKE_CASE : Optional[int] = tokens.expand(UpperCAmelCase_ , *tokens.shape[1:] ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat((tokens, next_tokens) , dim=1 ) else: SCREAMING_SNAKE_CASE : Tuple = -float(np.inf ) SCREAMING_SNAKE_CASE : List[str] = 0 SCREAMING_SNAKE_CASE : Dict = scores[:, None] + logits seq_lengths[~is_stopped] += 1 SCREAMING_SNAKE_CASE : Any = scores_sum / seq_lengths[:, None] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = scores_sum_average.view(-1 ).topk(UpperCAmelCase_ , -1 ) SCREAMING_SNAKE_CASE : str = next_tokens // scores_sum.shape[1] SCREAMING_SNAKE_CASE : Union[str, Any] = seq_lengths[next_tokens_source] SCREAMING_SNAKE_CASE : List[str] = next_tokens % scores_sum.shape[1] SCREAMING_SNAKE_CASE : Dict = next_tokens.unsqueeze(1 ) SCREAMING_SNAKE_CASE : Optional[Any] = tokens[next_tokens_source] SCREAMING_SNAKE_CASE : Optional[int] = torch.cat((tokens, next_tokens) , dim=1 ) SCREAMING_SNAKE_CASE : Any = generated[next_tokens_source] SCREAMING_SNAKE_CASE : Optional[int] = scores_sum_average * seq_lengths SCREAMING_SNAKE_CASE : Tuple = is_stopped[next_tokens_source] SCREAMING_SNAKE_CASE : int = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat((generated, next_token_embed) , dim=1 ) SCREAMING_SNAKE_CASE : Tuple = is_stopped + next_tokens.eq(UpperCAmelCase_ ).squeeze() if is_stopped.all(): break SCREAMING_SNAKE_CASE : List[str] = scores / seq_lengths SCREAMING_SNAKE_CASE : Tuple = scores.argsort(descending=UpperCAmelCase_ ) # tokens tensors are already padded to max_seq_length SCREAMING_SNAKE_CASE : int = [tokens[i] for i in order] SCREAMING_SNAKE_CASE : List[str] = torch.stack(UpperCAmelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
62
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 ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE : List[Any] = [144, 192, 240] SCREAMING_SNAKE_CASE : Tuple = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [96, 120, 144] SCREAMING_SNAKE_CASE : Dict = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [64, 80, 96] SCREAMING_SNAKE_CASE : List[str] = [16, 16, 24, 48, 64, 80, 320] SCREAMING_SNAKE_CASE : int = 0.05 SCREAMING_SNAKE_CASE : int = 2.0 if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : str = 512 SCREAMING_SNAKE_CASE : List[str] = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 21 SCREAMING_SNAKE_CASE : Dict = "pascal-voc-id2label.json" else: SCREAMING_SNAKE_CASE : Optional[Any] = 1000 SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : Any = "huggingface/label-files" SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowercase , lowercase , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE : List[str] = {int(lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} return config def lowerCamelCase__ ( lowercase , lowercase=False ): """simple docstring""" for i in range(1 , 6 ): if F'''layer_{i}.''' in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(F'''layer_{i}.''' , F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: SCREAMING_SNAKE_CASE : Dict = name.replace("conv_1." , "conv_stem." ) if ".block." in name: SCREAMING_SNAKE_CASE : List[str] = name.replace(".block." , "." ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE : str = name.replace("exp_1x1" , "expand_1x1" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("red_1x1" , "reduce_1x1" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".local_rep.conv_3x3." , ".conv_kxk." ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE : int = name.replace(".local_rep.conv_1x1." , ".conv_1x1." ) if ".norm." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".norm." , ".normalization." ) if ".conv." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".conv." , ".convolution." ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".conv_proj." , ".conv_projection." ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.layer.{j}.''' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.''' ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("expand_1x1" , "downsampling_layer.expand_1x1" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE : str = name.replace("conv_3x3" , "downsampling_layer.conv_3x3" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("reduce_1x1" , "downsampling_layer.reduce_1x1" ) for i in range(2 , 5 ): if F'''.global_rep.{i}.weight''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.global_rep.{i}.weight''' , ".layernorm.weight" ) if F'''.global_rep.{i}.bias''' in name: SCREAMING_SNAKE_CASE : str = name.replace(F'''.global_rep.{i}.bias''' , ".layernorm.bias" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".global_rep." , ".transformer." ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_mha.0." , ".layernorm_before." ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_mha.1.out_proj." , ".attention.output.dense." ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(".pre_norm_ffn.0." , ".layernorm_after." ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_ffn.1." , ".intermediate.dense." ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_ffn.4." , ".output.dense." ) if ".transformer." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".transformer." , ".transformer.layer." ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE : int = name.replace(".aspp_layer." , "." ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".aspp_pool." , "." ) if "seg_head." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("seg_head." , "segmentation_head." ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("segmentation_head.classifier.classifier." , "segmentation_head.classifier." ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("classifier.fc." , "classifier." ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE : List[Any] = "mobilevit." + name return name def lowerCamelCase__ ( lowercase , lowercase , lowercase=False ): """simple docstring""" if base_model: SCREAMING_SNAKE_CASE : Optional[int] = "" else: SCREAMING_SNAKE_CASE : Any = "mobilevit." for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = orig_state_dict.pop(lowercase ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE : int = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.split("." ) SCREAMING_SNAKE_CASE : Any = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE : List[Any] = int(key_split[3] ) SCREAMING_SNAKE_CASE : List[Any] = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) SCREAMING_SNAKE_CASE : int = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE : Union[str, Any] = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: SCREAMING_SNAKE_CASE : str = val[:dim] SCREAMING_SNAKE_CASE : Union[str, Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] else: SCREAMING_SNAKE_CASE : List[Any] = val return orig_state_dict def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_mobilevit_config(lowercase ) # load original state_dict SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(lowercase , map_location="cpu" ) # load 🤗 model if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : List[str] = MobileViTForSemanticSegmentation(lowercase ).eval() else: SCREAMING_SNAKE_CASE : str = MobileViTForImageClassification(lowercase ).eval() SCREAMING_SNAKE_CASE : Any = convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE : List[Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE : List[Any] = model(**lowercase ) SCREAMING_SNAKE_CASE : str = outputs.logits if mobilevit_name.startswith("deeplabv3_" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] , lowercase , atol=1E-4 ) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE : Dict = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] , lowercase , atol=1E-4 ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if push_to_hub: SCREAMING_SNAKE_CASE : List[str] = { "mobilevit_s": "mobilevit-small", "mobilevit_xs": "mobilevit-x-small", "mobilevit_xxs": "mobilevit-xx-small", "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small", "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small", "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small", } print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE : int = model_mapping[mobilevit_name] image_processor.push_to_hub(lowercase , organization="apple" ) model.push_to_hub(lowercase , organization="apple" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, 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 = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
62
1
snake_case = { """Pillow""": """Pillow<10.0.0""", """accelerate""": """accelerate>=0.20.3""", """av""": """av==9.2.0""", """beautifulsoup4""": """beautifulsoup4""", """black""": """black~=23.1""", """codecarbon""": """codecarbon==1.2.0""", """cookiecutter""": """cookiecutter==1.7.3""", """dataclasses""": """dataclasses""", """datasets""": """datasets!=2.5.0""", """decord""": """decord==0.6.0""", """deepspeed""": """deepspeed>=0.9.3""", """diffusers""": """diffusers""", """dill""": """dill<0.3.5""", """evaluate""": """evaluate>=0.2.0""", """fairscale""": """fairscale>0.3""", """faiss-cpu""": """faiss-cpu""", """fastapi""": """fastapi""", """filelock""": """filelock""", """flax""": """flax>=0.4.1,<=0.7.0""", """ftfy""": """ftfy""", """fugashi""": """fugashi>=1.0""", """GitPython""": """GitPython<3.1.19""", """hf-doc-builder""": """hf-doc-builder>=0.3.0""", """huggingface-hub""": """huggingface-hub>=0.14.1,<1.0""", """importlib_metadata""": """importlib_metadata""", """ipadic""": """ipadic>=1.0.0,<2.0""", """isort""": """isort>=5.5.4""", """jax""": """jax>=0.2.8,!=0.3.2,<=0.4.13""", """jaxlib""": """jaxlib>=0.1.65,<=0.4.13""", """jieba""": """jieba""", """kenlm""": """kenlm""", """keras-nlp""": """keras-nlp>=0.3.1""", """librosa""": """librosa""", """nltk""": """nltk""", """natten""": """natten>=0.14.6""", """numpy""": """numpy>=1.17""", """onnxconverter-common""": """onnxconverter-common""", """onnxruntime-tools""": """onnxruntime-tools>=1.4.2""", """onnxruntime""": """onnxruntime>=1.4.0""", """opencv-python""": """opencv-python""", """optuna""": """optuna""", """optax""": """optax>=0.0.8,<=0.1.4""", """packaging""": """packaging>=20.0""", """parameterized""": """parameterized""", """phonemizer""": """phonemizer""", """protobuf""": """protobuf""", """psutil""": """psutil""", """pyyaml""": """pyyaml>=5.1""", """pydantic""": """pydantic<2""", """pytest""": """pytest>=7.2.0""", """pytest-timeout""": """pytest-timeout""", """pytest-xdist""": """pytest-xdist""", """python""": """python>=3.8.0""", """ray[tune]""": """ray[tune]""", """regex""": """regex!=2019.12.17""", """requests""": """requests""", """rhoknp""": """rhoknp>=1.1.0,<1.3.1""", """rjieba""": """rjieba""", """rouge-score""": """rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1""", """ruff""": """ruff>=0.0.241,<=0.0.259""", """sacrebleu""": """sacrebleu>=1.4.12,<2.0.0""", """sacremoses""": """sacremoses""", """safetensors""": """safetensors>=0.3.1""", """sagemaker""": """sagemaker>=2.31.0""", """scikit-learn""": """scikit-learn""", """sentencepiece""": """sentencepiece>=0.1.91,!=0.1.92""", """sigopt""": """sigopt""", """starlette""": """starlette""", """sudachipy""": """sudachipy>=0.6.6""", """sudachidict_core""": """sudachidict_core>=20220729""", """tensorflow-cpu""": """tensorflow-cpu>=2.6,<2.14""", """tensorflow""": """tensorflow>=2.6,<2.14""", """tensorflow-text""": """tensorflow-text<2.14""", """tf2onnx""": """tf2onnx""", """timeout-decorator""": """timeout-decorator""", """timm""": """timm""", """tokenizers""": """tokenizers>=0.11.1,!=0.11.3,<0.14""", """torch""": """torch>=1.9,!=1.12.0""", """torchaudio""": """torchaudio""", """torchvision""": """torchvision""", """pyctcdecode""": """pyctcdecode>=0.4.0""", """tqdm""": """tqdm>=4.27""", """unidic""": """unidic>=1.0.2""", """unidic_lite""": """unidic_lite>=1.0.7""", """urllib3""": """urllib3<2.0.0""", """uvicorn""": """uvicorn""", }
62
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split snake_case = datasets.load_iris() snake_case = np.array(data["""data"""]) snake_case = np.array(data["""target"""]) snake_case = data["""target_names"""] snake_case , snake_case , snake_case , snake_case = train_test_split(X, y) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) ) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase=5 ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = zip(lowercase , lowercase ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE : Optional[int] = [] for data_point in data: SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE : List[Any] = [i[1] for i in sorted(lowercase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE : List[Any] = Counter(lowercase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
62
1
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : AutoencoderKL , UpperCAmelCase_ : CLIPTextModel , UpperCAmelCase_ : CLIPTokenizer , UpperCAmelCase_ : UNetaDConditionModel , UpperCAmelCase_ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , UpperCAmelCase_ : StableDiffusionSafetyChecker , UpperCAmelCase_ : CLIPImageProcessor , ): super().__init__() self.register_modules( vae=UpperCAmelCase_ , text_encoder=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , safety_checker=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , ) def _A ( self : Dict , UpperCAmelCase_ : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE : List[Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(UpperCAmelCase_ ) def _A ( self : str ): self.enable_attention_slicing(UpperCAmelCase_ ) @torch.no_grad() def __call__( self : Optional[int] , UpperCAmelCase_ : Union[str, List[str]] , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , **UpperCAmelCase_ : Dict , ): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = 1 elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : int = len(UpperCAmelCase_ ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_ )}''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(UpperCAmelCase_ )}.''' ) # get prompt text embeddings SCREAMING_SNAKE_CASE : Tuple = self.tokenizer( UpperCAmelCase_ , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) SCREAMING_SNAKE_CASE : List[str] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) SCREAMING_SNAKE_CASE : List[str] = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: SCREAMING_SNAKE_CASE : int = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = text_embeddings.shape SCREAMING_SNAKE_CASE : str = text_embeddings.repeat(1 , UpperCAmelCase_ , 1 ) SCREAMING_SNAKE_CASE : Dict = text_embeddings.view(bs_embed * num_images_per_prompt , UpperCAmelCase_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. SCREAMING_SNAKE_CASE : List[Any] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : List[str] if negative_prompt is None: SCREAMING_SNAKE_CASE : Optional[Any] = [""] elif type(UpperCAmelCase_ ) is not type(UpperCAmelCase_ ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(UpperCAmelCase_ )} !=''' f''' {type(UpperCAmelCase_ )}.''' ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = [negative_prompt] elif batch_size != len(UpperCAmelCase_ ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(UpperCAmelCase_ )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' " the batch size of `prompt`." ) else: SCREAMING_SNAKE_CASE : Tuple = negative_prompt SCREAMING_SNAKE_CASE : Any = text_input_ids.shape[-1] SCREAMING_SNAKE_CASE : Dict = self.tokenizer( UpperCAmelCase_ , padding="max_length" , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="pt" , ) SCREAMING_SNAKE_CASE : Dict = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE : List[Any] = uncond_embeddings.shape[1] SCREAMING_SNAKE_CASE : Optional[Any] = uncond_embeddings.repeat(UpperCAmelCase_ , UpperCAmelCase_ , 1 ) SCREAMING_SNAKE_CASE : Tuple = uncond_embeddings.view(batch_size * num_images_per_prompt , UpperCAmelCase_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. SCREAMING_SNAKE_CASE : str = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) SCREAMING_SNAKE_CASE : Union[str, Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) SCREAMING_SNAKE_CASE : List[Any] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps SCREAMING_SNAKE_CASE : Optional[Any] = torch.randn( UpperCAmelCase_ , generator=UpperCAmelCase_ , device="cpu" , dtype=UpperCAmelCase_ ).to(self.device ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.randn(UpperCAmelCase_ , generator=UpperCAmelCase_ , device="cpu" , dtype=UpperCAmelCase_ ).to( self.device ) else: SCREAMING_SNAKE_CASE : Any = torch.randn( UpperCAmelCase_ , generator=UpperCAmelCase_ , device=self.device , dtype=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.randn(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=self.device , dtype=UpperCAmelCase_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) SCREAMING_SNAKE_CASE : str = latents_reference.to(self.device ) SCREAMING_SNAKE_CASE : Union[str, Any] = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images SCREAMING_SNAKE_CASE : Union[str, Any] = (latents_shape[3] - latents_shape_reference[3]) // 2 SCREAMING_SNAKE_CASE : Optional[Any] = (latents_shape[2] - latents_shape_reference[2]) // 2 SCREAMING_SNAKE_CASE : int = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx SCREAMING_SNAKE_CASE : Union[str, Any] = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy SCREAMING_SNAKE_CASE : Optional[Any] = 0 if dx < 0 else dx SCREAMING_SNAKE_CASE : Union[str, Any] = 0 if dy < 0 else dy SCREAMING_SNAKE_CASE : Tuple = max(-dx , 0 ) SCREAMING_SNAKE_CASE : Tuple = max(-dy , 0 ) # import pdb # pdb.set_trace() SCREAMING_SNAKE_CASE : Dict = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand SCREAMING_SNAKE_CASE : Tuple = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE : List[Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] SCREAMING_SNAKE_CASE : Dict = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE : Optional[int] = {} if accepts_eta: SCREAMING_SNAKE_CASE : Dict = eta for i, t in enumerate(self.progress_bar(UpperCAmelCase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.scale_model_input(UpperCAmelCase_ , UpperCAmelCase_ ) # predict the noise residual SCREAMING_SNAKE_CASE : Optional[int] = self.unet(UpperCAmelCase_ , UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ ).sample # perform guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : str = self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 1 / 0.18_215 * latents SCREAMING_SNAKE_CASE : Any = self.vae.decode(UpperCAmelCase_ ).sample SCREAMING_SNAKE_CASE : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: SCREAMING_SNAKE_CASE : Any = self.feature_extractor(self.numpy_to_pil(UpperCAmelCase_ ) , return_tensors="pt" ).to( self.device ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.safety_checker( images=UpperCAmelCase_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: SCREAMING_SNAKE_CASE : List[Any] = None if output_type == "pil": SCREAMING_SNAKE_CASE : Optional[int] = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=UpperCAmelCase_ , nsfw_content_detected=UpperCAmelCase_ )
62
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''xlm-prophetnet''' UpperCamelCase_ : Tuple = ['''past_key_values'''] UpperCamelCase_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Dict , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[Union[str, Callable]] = "gelu" , UpperCAmelCase_ : Optional[int] = 3_0522 , UpperCAmelCase_ : Optional[int] = 1024 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[int] = 512 , UpperCAmelCase_ : Optional[float] = 0.02 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 2 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 128 , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[float] = 0.0 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 2 , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = num_encoder_layers SCREAMING_SNAKE_CASE : Any = num_encoder_attention_heads SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers SCREAMING_SNAKE_CASE : List[Any] = num_decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE : Dict = ngram SCREAMING_SNAKE_CASE : Any = num_buckets SCREAMING_SNAKE_CASE : str = relative_max_distance SCREAMING_SNAKE_CASE : str = disable_ngram_loss SCREAMING_SNAKE_CASE : Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : int = use_cache super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , add_cross_attention=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def _A ( self : int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
62
1