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
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCamelCase (a_ ): '''simple docstring''' @staticmethod @abstractmethod def __UpperCAmelCase ( _UpperCamelCase ) -> Union[str, Any]: raise NotImplementedError() @abstractmethod def __UpperCAmelCase ( self ) -> Any: raise NotImplementedError()
406
"""simple docstring""" import socket def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) UpperCAmelCase = socket.gethostname() UpperCAmelCase = 12312 sock.connect((host, port) ) sock.send(b"""Hello server!""" ) with open("""Received_file""" , """wb""" ) as out_file: print("""File opened""" ) print("""Receiving data...""" ) while True: UpperCAmelCase = sock.recv(1024 ) if not data: break out_file.write(lowerCAmelCase ) print("""Successfully received the file""" ) sock.close() print("""Connection closed""" ) if __name__ == "__main__": main()
673
0
"""simple docstring""" import fcntl import os import socket import torch import torch.distributed as dist def __a ( *A ) -> Tuple: '''simple docstring''' with open(A , "r" ) as fh: fcntl.flock(A , fcntl.LOCK_EX ) try: print(*A ) finally: fcntl.flock(A , fcntl.LOCK_UN ) __UpperCAmelCase =int(os.environ["""LOCAL_RANK"""]) torch.cuda.set_device(local_rank) __UpperCAmelCase =torch.device("""cuda""", local_rank) __UpperCAmelCase =socket.gethostname() __UpperCAmelCase =F'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group("""nccl""") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __UpperCAmelCase =dist.get_rank() __UpperCAmelCase =dist.get_world_size() printflock(F'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(F'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(F'''{gpu} is broken''') raise
337
"""simple docstring""" import math def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' return math.sqrt(lowerCAmelCase ) * math.sqrt(lowerCAmelCase ) == num def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = 0 UpperCAmelCase = n while left <= right: UpperCAmelCase = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: UpperCAmelCase = mid - 1 else: UpperCAmelCase = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
673
0
'''simple docstring''' import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class a__ : def __init__( self : Union[str, Any] , a : int , a : Tuple=13 , a : Union[str, Any]=7 , a : Optional[Any]=True , a : List[Any]=True , a : int=True , a : int=True , a : List[str]=99 , a : Any=32 , a : Union[str, Any]=5 , a : Optional[Any]=4 , a : Optional[int]=37 , a : Any="gelu" , a : Optional[int]=0.1 , a : Optional[int]=0.1 , a : List[Any]=5_12 , a : Union[str, Any]=16 , a : Dict=2 , a : List[Any]=0.02 , a : List[str]=3 , a : Tuple=4 , a : Tuple=None , ): """simple docstring""" __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_input_mask __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = scope def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase = None if self.use_input_mask: __lowerCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase = None if self.use_token_type_ids: __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None if self.use_labels: __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __lowerCamelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Any , a : Tuple , a : int , a : Any , a : List[Any] , a : Any , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = NystromformerModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() __lowerCamelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ ) __lowerCamelCase = model(snake_case__ , token_type_ids=snake_case__ ) __lowerCamelCase = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Optional[int] , a : List[str] , a : Tuple , a : str , a : Any , a : int , a : Tuple ): """simple docstring""" __lowerCamelCase = NystromformerForMaskedLM(config=snake_case__ ) model.to(snake_case__ ) model.eval() __lowerCamelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : Dict , a : List[str] , a : str , a : int , a : str , a : List[Any] , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = NystromformerForQuestionAnswering(config=snake_case__ ) model.to(snake_case__ ) model.eval() __lowerCamelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : Dict , a : Optional[int] , a : int , a : Tuple , a : Dict , a : Optional[int] , a : Any ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = NystromformerForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() __lowerCamelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Optional[int] , a : int , a : Optional[int] , a : Optional[int] , a : Optional[int] , a : str , a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = NystromformerForTokenClassification(config=snake_case__ ) model.to(snake_case__ ) model.eval() __lowerCamelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Optional[Any] , a : List[Any] , a : Dict , a : List[Any] , a : Union[str, Any] , a : List[Any] , a : List[Any] ): """simple docstring""" __lowerCamelCase = self.num_choices __lowerCamelCase = NystromformerForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() __lowerCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) = config_and_inputs __lowerCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class a__ ( a_ , a_ , unittest.TestCase ): lowerCamelCase : Optional[Any] =( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) lowerCamelCase : Optional[Any] =( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase : int =False lowerCamelCase : Dict =False def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = NystromformerModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=snake_case__ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase = type self.model_tester.create_and_check_model(*snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = NystromformerModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) @require_torch class a__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = NystromformerModel.from_pretrained('''uw-madison/nystromformer-512''' ) __lowerCamelCase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __lowerCamelCase = model(snake_case__ )[0] __lowerCamelCase = torch.Size((1, 6, 7_68) ) self.assertEqual(output.shape , snake_case__ ) __lowerCamelCase = torch.tensor( [[[-0.45_32, -0.09_36, 0.51_37], [-0.26_76, 0.06_28, 0.61_86], [-0.36_29, -0.17_26, 0.47_16]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = '''the [MASK] of Belgium is Brussels''' __lowerCamelCase = AutoTokenizer.from_pretrained('''uw-madison/nystromformer-512''' ) __lowerCamelCase = NystromformerForMaskedLM.from_pretrained('''uw-madison/nystromformer-512''' ) __lowerCamelCase = tokenizer(snake_case__ , return_tensors='''pt''' ) with torch.no_grad(): __lowerCamelCase = model(encoding.input_ids ).logits __lowerCamelCase = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(snake_case__ ) , '''capital''' )
546
"""simple docstring""" import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _lowerCAmelCase ( *lowerCAmelCase ): '''simple docstring''' if not isinstance(lowerCAmelCase , lowerCAmelCase ): UpperCAmelCase = list(lowerCAmelCase ) for i in range(len(lowerCAmelCase ) ): UpperCAmelCase = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(lowerCAmelCase , lowerCAmelCase ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _lowerCAmelCase ( lowerCAmelCase = None , lowerCAmelCase = 128 ): '''simple docstring''' if function is None: return functools.partial(lowerCAmelCase , starting_batch_size=lowerCAmelCase ) UpperCAmelCase = starting_batch_size def decorator(*lowerCAmelCase , **lowerCAmelCase ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() UpperCAmelCase = list(inspect.signature(lowerCAmelCase ).parameters.keys() ) # Guard against user error if len(lowerCAmelCase ) < (len(lowerCAmelCase ) + 1): UpperCAmelCase = """, """.join([F'''{arg}={value}''' for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F'''Batch size was passed into `{function.__name__}` as the first argument when called.''' F'''Remove this as the decorator already does so: `{function.__name__}({arg_str})`''' ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(lowerCAmelCase , *lowerCAmelCase , **lowerCAmelCase ) except Exception as e: if should_reduce_batch_size(lowerCAmelCase ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
673
0
import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler') class A : def __init__( self : str , lowercase_ : Optional[Any] , lowercase_ : List[str] , lowercase_ : Tuple = True , lowercase_ : Optional[Any] = False ) -> int: """simple docstring""" _lowerCamelCase : List[Any] =scheduler _lowerCamelCase : Dict =optimizers if isinstance(snake_case__ , (list, tuple) ) else [optimizers] _lowerCamelCase : List[str] =split_batches _lowerCamelCase : Tuple =step_with_optimizer _lowerCamelCase : Any =GradientState() def lowerCamelCase ( self : Any , *lowercase_ : Optional[int] , **lowercase_ : int ) -> Dict: """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*snake_case__ , **snake_case__ ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*snake_case__ , **snake_case__ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step _lowerCamelCase : Optional[Any] =AcceleratorState().num_processes for _ in range(snake_case__ ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , 'total_steps' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*snake_case__ , **snake_case__ ) else: self.scheduler.step(*snake_case__ , **snake_case__ ) def lowerCamelCase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" return self.scheduler.get_last_lr() def lowerCamelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" return self.scheduler.state_dict() def lowerCamelCase ( self : Tuple , lowercase_ : Optional[int] ) -> List[str]: """simple docstring""" self.scheduler.load_state_dict(snake_case__ ) def lowerCamelCase ( self : Tuple ) -> Tuple: """simple docstring""" return self.scheduler.get_lr() def lowerCamelCase ( self : Optional[int] , *lowercase_ : int , **lowercase_ : int ) -> Tuple: """simple docstring""" return self.scheduler.print_lr(*snake_case__ , **snake_case__ )
464
"""simple docstring""" import math def _lowerCAmelCase ( lowerCAmelCase = 100 ): '''simple docstring''' UpperCAmelCase = sum(i * i for i in range(1 , n + 1 ) ) UpperCAmelCase = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F'{solution() = }')
673
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Dict = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
567
"""simple docstring""" def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [0] * len(lowerCAmelCase ) UpperCAmelCase = [] UpperCAmelCase = [1] * len(lowerCAmelCase ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCAmelCase ) ): if indegree[i] == 0: queue.append(lowerCAmelCase ) while queue: UpperCAmelCase = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: UpperCAmelCase = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(lowerCAmelCase ) print(max(lowerCAmelCase ) ) # Adjacency list of Graph lowerCAmelCase_ : str = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
673
0
'''simple docstring''' def lowerCAmelCase_ ( ): return [ a * b * (10_00 - a - b) for a in range(1 , 9_99 ) for b in range(_lowerCamelCase , 9_99 ) if (a * a + b * b == (10_00 - a - b) ** 2) ][0] if __name__ == "__main__": print(f"{solution() = }")
578
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase_ ( a_ ): _A : Optional[int] = 'facebook/bart-large-mnli' _A : Union[str, Any] = ( 'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ' 'should be the text to classify, and `labels`, which should be the list of labels to use for classification. ' 'It returns the most likely label in the list of provided `labels` for the input text.' ) _A : Dict = 'text_classifier' _A : Union[str, Any] = AutoTokenizer _A : Tuple = AutoModelForSequenceClassification _A : Optional[int] = ['text', ['text']] _A : Dict = ['text'] def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" super().setup() UpperCAmelCase = self.model.config UpperCAmelCase = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): UpperCAmelCase = int(snake_case__ ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = labels return self.pre_processor( [text] * len(snake_case__ ) , [f'''This example is {label}''' for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def UpperCamelCase_ ( self , snake_case__ ) -> str: """simple docstring""" UpperCAmelCase = outputs.logits UpperCAmelCase = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
673
0
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __lowercase ( ): snake_case_ : List[str] = ArgumentParser( description=( '''PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=_a , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=_a , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=_a ) return parser.parse_args() def __lowercase ( ): snake_case_ : str = parse_args() # Import training_script as a module. snake_case_ : int = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) snake_case_ : Any = script_fpath.stem snake_case_ : int = importlib.import_module(_a ) # Patch sys.argv snake_case_ : Tuple = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
123
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class UpperCamelCase_ ( a_ ): _A : Union[List[PIL.Image.Image], np.ndarray] _A : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
673
0
'''simple docstring''' from __future__ import annotations def __A ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) __SCREAMING_SNAKE_CASE : List[Any] = result + left + right return input_list def __A ( _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) <= 1: return input_list __SCREAMING_SNAKE_CASE : Tuple = list(_SCREAMING_SNAKE_CASE ) # iteration for two-way merging __SCREAMING_SNAKE_CASE : List[Any] = 2 while p <= len(_SCREAMING_SNAKE_CASE ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE : Optional[Any] = i __SCREAMING_SNAKE_CASE : List[str] = i + p - 1 __SCREAMING_SNAKE_CASE : Union[str, Any] = (low + high + 1) // 2 __SCREAMING_SNAKE_CASE : Any = merge(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # final merge of last two parts if p * 2 >= len(_SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE : Tuple = i __SCREAMING_SNAKE_CASE : Any = merge(_SCREAMING_SNAKE_CASE , 0 , _SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": lowercase = input('''Enter numbers separated by a comma:\n''').strip() if user_input == "": lowercase = [] else: lowercase = [int(item.strip()) for item in user_input.split(''',''')] print(iter_merge_sort(unsorted))
211
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCAmelCase_ : Any = { '''configuration_encodec''': [ '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EncodecConfig''', ], '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EncodecModel''', '''EncodecPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
673
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer __a: List[Any] = logging.get_logger(__name__) __a: List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __a: Union[str, Any] = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } __a: Tuple = {'''mobilebert-uncased''': 5_12} __a: List[Any] = {} class UpperCAmelCase ( a_ ): '''simple docstring''' SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE = MobileBertTokenizer def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=True , __lowerCAmelCase="[UNK]" , __lowerCAmelCase="[SEP]" , __lowerCAmelCase="[PAD]" , __lowerCAmelCase="[CLS]" , __lowerCAmelCase="[MASK]" , __lowerCAmelCase=True , __lowerCAmelCase=None , **__lowerCAmelCase , ) -> Optional[Any]: super().__init__( snake_case__ , tokenizer_file=snake_case__ , do_lower_case=snake_case__ , unk_token=snake_case__ , sep_token=snake_case__ , pad_token=snake_case__ , cls_token=snake_case__ , mask_token=snake_case__ , tokenize_chinese_chars=snake_case__ , strip_accents=snake_case__ , **snake_case__ , ) lowercase__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , snake_case__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , snake_case__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , snake_case__ ) != tokenize_chinese_chars ): lowercase__ : int = getattr(snake_case__ , normalizer_state.pop('''type''' ) ) lowercase__ : Dict = do_lower_case lowercase__ : Optional[int] = strip_accents lowercase__ : Optional[int] = tokenize_chinese_chars lowercase__ : Tuple = normalizer_class(**snake_case__ ) lowercase__ : int = do_lower_case def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase=None ) -> Dict: lowercase__ : int = [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 _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase = None ) -> List[int]: lowercase__ : Dict = [self.sep_token_id] lowercase__ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase = None ) -> Tuple[str]: lowercase__ : Any = self._tokenizer.model.save(snake_case__ , name=snake_case__ ) return tuple(snake_case__ )
152
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
673
0
'''simple docstring''' 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 __UpperCamelCase : def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=64 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ): '''simple docstring''' __a : int = parent __a : List[Any] = batch_size __a : Tuple = seq_length __a : List[str] = is_training __a : str = use_input_mask __a : str = use_token_type_ids __a : Optional[int] = use_labels __a : Any = vocab_size __a : Optional[Any] = hidden_size __a : Union[str, Any] = embedding_size __a : List[Any] = num_hidden_layers __a : int = num_attention_heads __a : Dict = intermediate_size __a : int = hidden_act __a : Optional[int] = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : int = max_position_embeddings __a : int = type_vocab_size __a : Optional[int] = type_sequence_label_size __a : List[Any] = initializer_range __a : Dict = num_labels __a : Optional[int] = num_choices __a : Optional[int] = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : Dict = None if self.use_input_mask: __a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __a : Tuple = None if self.use_token_type_ids: __a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : str = None __a : Tuple = None __a : List[Any] = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) __a : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): '''simple docstring''' 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=snake_case__ , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Tuple = MegatronBertModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : Optional[Any] = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ ) __a : List[Any] = model(snake_case__ , token_type_ids=snake_case__ ) __a : int = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Union[str, Any] = MegatronBertForMaskedLM(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : int = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = MegatronBertForCausalLM(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : Tuple = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = MegatronBertForNextSentencePrediction(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : Tuple = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = MegatronBertForPreTraining(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : Optional[int] = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , next_sentence_label=snake_case__ , ) 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 __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[Any] = MegatronBertForQuestionAnswering(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : List[str] = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Optional[Any] = self.num_labels __a : Tuple = MegatronBertForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() __a : List[Any] = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : List[str] = self.num_labels __a : str = MegatronBertForTokenClassification(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : Any = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a ): '''simple docstring''' __a : Union[str, Any] = self.num_choices __a : str = MegatronBertForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() __a : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : str = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Any = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Union[str, Any] = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Optional[Any] = config_and_inputs __a : str = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( a_ , a_ , unittest.TestCase ): A_ = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) A_ = ( { '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 {} ) A_ = True # test_resize_embeddings = False A_ = False def __UpperCAmelCase ( self , __a , __a , __a=False ): '''simple docstring''' __a : int = super()._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) if return_labels: if model_class in get_values(snake_case__ ): __a : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=snake_case__ ) __a : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) return inputs_dict def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = MegatronBertModelTester(self ) __a : Dict = ConfigTester(self , config_class=snake_case__ , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*snake_case__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*snake_case__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*snake_case__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*snake_case__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*snake_case__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*snake_case__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*snake_case__ ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*snake_case__ ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): return torch.tensor( _SCREAMING_SNAKE_CASE , dtype=torch.long , device=_SCREAMING_SNAKE_CASE , ) __lowercase : List[Any] = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): @slow @unittest.skip('Model is not available.' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = 'nvidia/megatron-bert-uncased-345m' if "MYDIR" in os.environ: __a : int = os.path.join(os.environ['MYDIR'] , snake_case__ ) __a : List[Any] = MegatronBertModel.from_pretrained(snake_case__ ) model.to(snake_case__ ) model.half() __a : List[str] = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] ) with torch.no_grad(): __a : Dict = model(snake_case__ )[0] __a : Dict = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape , snake_case__ ) __a : Dict = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): __a : Dict = output[0, ii, jj] __a : Dict = expected[3 * ii + jj] __a : str = 'ii={} jj={} a={} b={}'.format(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) self.assertTrue(math.isclose(snake_case__ , snake_case__ , rel_tol=snake_case__ , abs_tol=snake_case__ ) , msg=snake_case__ )
476
"""simple docstring""" import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : str = VideoToVideoSDPipeline _A : List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'} ) - {'image', 'width', 'height'} _A : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'} ) - {'image'} _A : int = PipelineTesterMixin.required_optional_params - {'latents'} _A : List[str] = False # No `output_type`. _A : Any = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'return_dict', 'callback', 'callback_steps', ] ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) UpperCAmelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=snake_case__ , set_alpha_to_one=snake_case__ , ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="""gelu""" , projection_dim=5_12 , ) UpperCAmelCase = CLIPTextModel(snake_case__ ) UpperCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCAmelCase = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def UpperCamelCase_ ( self , snake_case__ , snake_case__=0 ) -> List[str]: """simple docstring""" UpperCAmelCase = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) if str(snake_case__ ).startswith("""mps""" ): UpperCAmelCase = torch.manual_seed(snake_case__ ) else: UpperCAmelCase = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) UpperCAmelCase = { """prompt""": """A painting of a squirrel eating a burger""", """video""": video, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = VideoToVideoSDPipeline(**snake_case__ ) UpperCAmelCase = sd_pipe.to(snake_case__ ) sd_pipe.set_progress_bar_config(disable=snake_case__ ) UpperCAmelCase = self.get_dummy_inputs(snake_case__ ) UpperCAmelCase = """np""" UpperCAmelCase = sd_pipe(**snake_case__ ).frames UpperCAmelCase = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) UpperCAmelCase = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=snake_case__ , expected_max_diff=5e-3 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return super().test_progress_bar() @slow @skip_mps class UpperCamelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = VideoToVideoSDPipeline.from_pretrained("""cerspense/zeroscope_v2_XL""" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames UpperCAmelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCAmelCase = torch.randn((1, 10, 3, 10_24, 5_76) , generator=snake_case__ ) UpperCAmelCase = video.to("""cuda""" ) UpperCAmelCase = """Spiderman is surfing""" UpperCAmelCase = pipe(snake_case__ , video=snake_case__ , generator=snake_case__ , num_inference_steps=3 , output_type="""pt""" ).frames UpperCAmelCase = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
673
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { '''configuration_mgp_str''': ['''MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MgpstrConfig'''], '''processing_mgp_str''': ['''MgpstrProcessor'''], '''tokenization_mgp_str''': ['''MgpstrTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MgpstrModel''', '''MgpstrPreTrainedModel''', '''MgpstrForSceneTextRecognition''', ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
393
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : int = logging.get_logger(__name__) lowerCAmelCase_ : Any = { '''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''', # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class UpperCamelCase_ ( a_ ): _A : int = 'wav2vec2' def __init__( self , snake_case__=32 , snake_case__=7_68 , snake_case__=12 , snake_case__=12 , snake_case__=30_72 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.02 , snake_case__=1e-5 , snake_case__="group" , snake_case__="gelu" , snake_case__=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , snake_case__=(5, 2, 2, 2, 2, 2, 2) , snake_case__=(10, 3, 3, 3, 3, 2, 2) , snake_case__=False , snake_case__=1_28 , snake_case__=16 , snake_case__=False , snake_case__=True , snake_case__=0.05 , snake_case__=10 , snake_case__=2 , snake_case__=0.0 , snake_case__=10 , snake_case__=0 , snake_case__=3_20 , snake_case__=2 , snake_case__=0.1 , snake_case__=1_00 , snake_case__=2_56 , snake_case__=2_56 , snake_case__=0.1 , snake_case__="sum" , snake_case__=False , snake_case__=False , snake_case__=2_56 , snake_case__=(5_12, 5_12, 5_12, 5_12, 15_00) , snake_case__=(5, 3, 3, 1, 1) , snake_case__=(1, 2, 3, 1, 1) , snake_case__=5_12 , snake_case__=0 , snake_case__=1 , snake_case__=2 , snake_case__=False , snake_case__=3 , snake_case__=2 , snake_case__=3 , snake_case__=None , snake_case__=None , **snake_case__ , ) -> Optional[Any]: """simple docstring""" super().__init__(**snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ ) UpperCAmelCase = hidden_size UpperCAmelCase = feat_extract_norm UpperCAmelCase = feat_extract_activation UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = conv_bias UpperCAmelCase = num_conv_pos_embeddings UpperCAmelCase = num_conv_pos_embedding_groups UpperCAmelCase = len(self.conv_dim ) UpperCAmelCase = num_hidden_layers UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = feat_proj_dropout UpperCAmelCase = final_dropout UpperCAmelCase = layerdrop UpperCAmelCase = layer_norm_eps UpperCAmelCase = initializer_range UpperCAmelCase = vocab_size UpperCAmelCase = do_stable_layer_norm UpperCAmelCase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks # parameters for pretraining with codevector quantized representations UpperCAmelCase = num_codevectors_per_group UpperCAmelCase = num_codevector_groups UpperCAmelCase = contrastive_logits_temperature UpperCAmelCase = feat_quantizer_dropout UpperCAmelCase = num_negatives UpperCAmelCase = codevector_dim UpperCAmelCase = proj_codevector_dim UpperCAmelCase = diversity_loss_weight # ctc loss UpperCAmelCase = ctc_loss_reduction UpperCAmelCase = ctc_zero_infinity # adapter UpperCAmelCase = add_adapter UpperCAmelCase = adapter_kernel_size UpperCAmelCase = adapter_stride UpperCAmelCase = num_adapter_layers UpperCAmelCase = output_hidden_size or hidden_size UpperCAmelCase = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = xvector_output_dim @property def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
673
0
def lowercase__ ( ): '''simple docstring''' UpperCAmelCase_ : Any = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] UpperCAmelCase_ : List[Any] = 6 UpperCAmelCase_ : Optional[int] = 1 UpperCAmelCase_ : Any = 1_901 UpperCAmelCase_ : int = 0 while year < 2_001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 UpperCAmelCase_ : Dict = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 UpperCAmelCase_ : Any = day - 29 else: if day > days_per_month[month - 1]: month += 1 UpperCAmelCase_ : Optional[int] = day - days_per_month[month - 2] if month > 12: year += 1 UpperCAmelCase_ : List[str] = 1 if year < 2_001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
406
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowerCAmelCase_ : Optional[Any] = NewType('''DataClass''', Any) lowerCAmelCase_ : Any = NewType('''DataClassType''', Any) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' if isinstance(lowerCAmelCase , lowerCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = {str(lowerCAmelCase ): choice for choice in choices} return lambda lowerCAmelCase : str_to_choice.get(lowerCAmelCase , lowerCAmelCase ) def _lowerCAmelCase ( *, lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = dataclasses.MISSING , lowerCAmelCase = dataclasses.MISSING , lowerCAmelCase = None , **lowerCAmelCase , ): '''simple docstring''' if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls UpperCAmelCase = {} if aliases is not None: UpperCAmelCase = aliases if help is not None: UpperCAmelCase = help return dataclasses.field(metadata=lowerCAmelCase , default=lowerCAmelCase , default_factory=lowerCAmelCase , **lowerCAmelCase ) class UpperCamelCase_ ( a_ ): _A : Iterable[DataClassType] def __init__( self , snake_case__ , **snake_case__ ) -> List[str]: """simple docstring""" if "formatter_class" not in kwargs: UpperCAmelCase = ArgumentDefaultsHelpFormatter super().__init__(**snake_case__ ) if dataclasses.is_dataclass(snake_case__ ): UpperCAmelCase = [dataclass_types] UpperCAmelCase = list(snake_case__ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(snake_case__ ) @staticmethod def UpperCamelCase_ ( snake_case__ , snake_case__ ) -> str: """simple docstring""" UpperCAmelCase = f'''--{field.name}''' UpperCAmelCase = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , snake_case__ ): raise RuntimeError( """Unresolved type detected, which should have been done with the help of """ """`typing.get_type_hints` method by default""" ) UpperCAmelCase = kwargs.pop("""aliases""" , [] ) if isinstance(snake_case__ , snake_case__ ): UpperCAmelCase = [aliases] UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) if origin_type is Union or (hasattr(snake_case__ , """UnionType""" ) and isinstance(snake_case__ , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(snake_case__ ) not in field.type.__args__ ): raise ValueError( """Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because""" """ the argument parser only supports one type per argument.""" f''' Problem encountered in field \'{field.name}\'.''' ) if type(snake_case__ ) not in field.type.__args__: # filter `str` in Union UpperCAmelCase = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) UpperCAmelCase = ( field.type.__args__[0] if isinstance(snake_case__ , field.type.__args__[1] ) else field.type.__args__[1] ) UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) UpperCAmelCase = {} if origin_type is Literal or (isinstance(field.type , snake_case__ ) and issubclass(field.type , snake_case__ )): if origin_type is Literal: UpperCAmelCase = field.type.__args__ else: UpperCAmelCase = [x.value for x in field.type] UpperCAmelCase = make_choice_type_function(kwargs["""choices"""] ) if field.default is not dataclasses.MISSING: UpperCAmelCase = field.default else: UpperCAmelCase = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument UpperCAmelCase = copy(snake_case__ ) # Hack because type=bool in argparse does not behave as we want. UpperCAmelCase = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. UpperCAmelCase = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way UpperCAmelCase = default # This tells argparse we accept 0 or 1 value after --field_name UpperCAmelCase = """?""" # This is the value that will get picked if we do --field_name (without value) UpperCAmelCase = True elif isclass(snake_case__ ) and issubclass(snake_case__ , snake_case__ ): UpperCAmelCase = field.type.__args__[0] UpperCAmelCase = """+""" if field.default_factory is not dataclasses.MISSING: UpperCAmelCase = field.default_factory() elif field.default is dataclasses.MISSING: UpperCAmelCase = True else: UpperCAmelCase = field.type if field.default is not dataclasses.MISSING: UpperCAmelCase = field.default elif field.default_factory is not dataclasses.MISSING: UpperCAmelCase = field.default_factory() else: UpperCAmelCase = True parser.add_argument(snake_case__ , *snake_case__ , **snake_case__ ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): UpperCAmelCase = False parser.add_argument(f'''--no_{field.name}''' , action="""store_false""" , dest=field.name , **snake_case__ ) def UpperCamelCase_ ( self , snake_case__ ) -> Any: """simple docstring""" if hasattr(snake_case__ , """_argument_group_name""" ): UpperCAmelCase = self.add_argument_group(dtype._argument_group_name ) else: UpperCAmelCase = self try: UpperCAmelCase = get_type_hints(snake_case__ ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' """removing line of `from __future__ import annotations` which opts in Postponed """ """Evaluation of Annotations (PEP 563)""" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(snake_case__ ): UpperCAmelCase = """.""".join(map(snake_case__ , sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' """line of `from __future__ import annotations` which opts in union types as """ """`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To """ """support Python versions that lower than 3.10, you need to use """ """`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of """ """`X | None`.""" ) from ex raise for field in dataclasses.fields(snake_case__ ): if not field.init: continue UpperCAmelCase = type_hints[field.name] self._parse_dataclass_field(snake_case__ , snake_case__ ) def UpperCamelCase_ ( self , snake_case__=None , snake_case__=False , snake_case__=True , snake_case__=None , snake_case__=None , ) -> Tuple[DataClass, ...]: """simple docstring""" if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): UpperCAmelCase = [] if args_filename: args_files.append(Path(snake_case__ ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(""".args""" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values UpperCAmelCase = ArgumentParser() args_file_parser.add_argument(snake_case__ , type=snake_case__ , action="""append""" ) # Use only remaining args for further parsing (remove the args_file_flag) UpperCAmelCase , UpperCAmelCase = args_file_parser.parse_known_args(args=snake_case__ ) UpperCAmelCase = vars(snake_case__ ).get(args_file_flag.lstrip("""-""" ) , snake_case__ ) if cmd_args_file_paths: args_files.extend([Path(snake_case__ ) for p in cmd_args_file_paths] ) UpperCAmelCase = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last UpperCAmelCase = file_args + args if args is not None else file_args + sys.argv[1:] UpperCAmelCase , UpperCAmelCase = self.parse_known_args(args=snake_case__ ) UpperCAmelCase = [] for dtype in self.dataclass_types: UpperCAmelCase = {f.name for f in dataclasses.fields(snake_case__ ) if f.init} UpperCAmelCase = {k: v for k, v in vars(snake_case__ ).items() if k in keys} for k in keys: delattr(snake_case__ , snake_case__ ) UpperCAmelCase = dtype(**snake_case__ ) outputs.append(snake_case__ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(snake_case__ ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" UpperCAmelCase = set(args.keys() ) UpperCAmelCase = [] for dtype in self.dataclass_types: UpperCAmelCase = {f.name for f in dataclasses.fields(snake_case__ ) if f.init} UpperCAmelCase = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) UpperCAmelCase = dtype(**snake_case__ ) outputs.append(snake_case__ ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(snake_case__ )}''' ) return tuple(snake_case__ ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" with open(Path(snake_case__ ) , encoding="""utf-8""" ) as open_json_file: UpperCAmelCase = json.loads(open_json_file.read() ) UpperCAmelCase = self.parse_dict(snake_case__ , allow_extra_keys=snake_case__ ) return tuple(snake_case__ ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" UpperCAmelCase = self.parse_dict(yaml.safe_load(Path(snake_case__ ).read_text() ) , allow_extra_keys=snake_case__ ) return tuple(snake_case__ )
673
0
"""simple docstring""" import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __a ( A , A , A , A=False ) -> Dict: '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise if not is_sharded: A__ = os.path.abspath(A ) logger.info(f"""Loading PyTorch weights from {pt_path}""" ) A__ = torch.load(A , map_location="cpu" ) logger.info(f"""PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters.""" ) A__ = convert_pytorch_state_dict_to_flax(A , A ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files A__ = convert_pytorch_sharded_state_dict_to_flax(A , A ) return flax_state_dict def __a ( A , A , A , A , ) -> List[Any]: '''simple docstring''' def is_key_or_prefix_key_in_dict(A ) -> bool: return len(set(A ) & {key, (model_prefix,) + key} ) > 0 # layer norm A__ = pt_tuple_key[:-1] + ("scale",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(A ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean A__ = pt_tuple_key[:-1] + ("mean",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(A ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var A__ = pt_tuple_key[:-1] + ("var",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(A ): return renamed_pt_tuple_key, pt_tensor # embedding A__ = pt_tuple_key[:-1] + ("embedding",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(A ): return renamed_pt_tuple_key, pt_tensor # conv layer A__ = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(A ): A__ = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer A__ = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(A ): A__ = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight A__ = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias A__ = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 A__ = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): A__ = pt_tuple_key[-2] + "_g" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): A__ = pt_tuple_key[-2] + "_v" if name is not None: A__ = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def __a ( A , A ) -> Any: '''simple docstring''' A__ = {k: v.numpy() for k, v in pt_state_dict.items()} A__ = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: A__ = flax_model.params["params"] else: A__ = flax_model.params A__ = flatten_dict(A ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: A__ = flatten_dict(flax_model.params["batch_stats"] ) random_flax_state_dict.update(A ) A__ = {} A__ = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) A__ = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): A__ = tuple(pt_key.split("." ) ) # remove base model prefix if necessary A__ = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: A__ = pt_tuple_key[1:] # Correctly rename weight parameters A__ , A__ = rename_key_and_reshape_tensor( A , A , A , A ) # add model prefix if necessary A__ = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: A__ = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """ f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: A__ = jnp.asarray(A ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(A , A ) continue # also add unexpected weight so that warning is thrown A__ = jnp.asarray(A ) else: # also add unexpected weight so that warning is thrown A__ = jnp.asarray(A ) return unflatten_dict(A ) def __a ( A , A ) -> Optional[Any]: '''simple docstring''' import torch # Load the index A__ = {} for shard_file in shard_filenames: # load using msgpack utils A__ = torch.load(A ) A__ = {k: v.numpy() for k, v in pt_state_dict.items()} A__ = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: A__ = flax_model.params["params"] A__ = flatten_dict(A ) random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"] ) ) else: A__ = flax_model.params A__ = flatten_dict(A ) A__ = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) A__ = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): A__ = tuple(pt_key.split("." ) ) # remove base model prefix if necessary A__ = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: A__ = pt_tuple_key[1:] # Correctly rename weight parameters A__ , A__ = rename_key_and_reshape_tensor( A , A , A , A ) # add model prefix if necessary A__ = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: A__ = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """ f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: A__ = jnp.asarray(A ) continue if "var" in flax_key[-1]: A__ = jnp.asarray(A ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(A , A ) continue # also add unexpected weight so that warning is thrown A__ = jnp.asarray(A ) else: # also add unexpected weight so that warning is thrown A__ = jnp.asarray(A ) return unflatten_dict(A ) def __a ( A , A ) -> Optional[int]: '''simple docstring''' A__ = os.path.abspath(A ) logger.info(f"""Loading Flax weights from {flax_checkpoint_path}""" ) # import correct flax class A__ = getattr(A , "Flax" + model.__class__.__name__ ) # load flax weight dict with open(A , "rb" ) as state_f: try: A__ = from_bytes(A , state_f.read() ) except UnpicklingError: raise EnvironmentError(f"""Unable to convert {flax_checkpoint_path} to Flax deserializable object. """ ) return load_flax_weights_in_pytorch_model(A , A ) def __a ( A , A ) -> Union[str, Any]: '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( "Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights A__ = flatten_dict(jax.tree_util.tree_map(lambda A : x.dtype == jnp.bfloataa , A ) ).values() if any(A ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) A__ = jax.tree_util.tree_map( lambda A : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , A ) A__ = flatten_dict(A ) A__ = pt_model.state_dict() A__ = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split("." )[0] for k in pt_model_dict.keys()} ) A__ = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split("." )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys A__ = [] A__ = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): A__ = flax_key_tuple[0] == pt_model.base_model_prefix A__ = ".".join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: A__ = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: A__ = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(A ) not in pt_model_dict: # conv layer A__ = flax_key_tuple[:-1] + ("weight",) A__ = jnp.transpose(A , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(A ) not in pt_model_dict: # linear layer A__ = flax_key_tuple[:-1] + ("weight",) A__ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A__ = flax_key_tuple[:-1] + ("weight",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: A__ = flax_key_tuple[:-1] + ("running_mean",) elif "var" in flax_key_tuple[-1]: A__ = flax_key_tuple[:-1] + ("running_var",) if "batch_stats" in flax_state: A__ = ".".join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: A__ = ".".join(A ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. A__ = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: A__ = key.split("." ) A__ = None if key_components[-3::2] == ["parametrizations", "original0"]: A__ = key_components[-2] + "_g" elif key_components[-3::2] == ["parametrizations", "original1"]: A__ = key_components[-2] + "_v" if name is not None: A__ = key_components[:-3] + [name] A__ = ".".join(A ) A__ = key if flax_key in special_pt_names: A__ = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f"""Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected """ f"""to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) else: # add weight to pytorch dict A__ = np.asarray(A ) if not isinstance(A , np.ndarray ) else flax_tensor A__ = torch.from_numpy(A ) # remove from missing keys missing_keys.remove(A ) else: # weight is not expected by PyTorch model unexpected_keys.append(A ) pt_model.load_state_dict(A ) # re-transform missing_keys to list A__ = list(A ) if len(A ) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" f""" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing""" f""" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture""" " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" f""" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect""" " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) else: logger.warning(f"""All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n""" ) if len(A ) > 0: logger.warning( f"""Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly""" f""" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to""" " use it for predictions and inference." ) else: logger.warning( f"""All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n""" "If your task is similar to the task the model of the checkpoint was trained on, " f"""you can already use {pt_model.__class__.__name__} for predictions without further training.""" ) return pt_model
337
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCAmelCase_ : List[str] = False class UpperCamelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self , snake_case__=32 ) -> Optional[Any]: """simple docstring""" set_seed(0 ) UpperCAmelCase = UNetaDModel(sample_size=snake_case__ , in_channels=3 , out_channels=3 ) UpperCAmelCase = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable UpperCAmelCase = DDPMScheduler( num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) UpperCAmelCase = DDIMScheduler( num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) UpperCAmelCase = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(snake_case__ ) for _ in range(4 )] UpperCAmelCase = [torch.randn((4, 3, 32, 32) ).to(snake_case__ ) for _ in range(4 )] UpperCAmelCase = [torch.randint(0 , 10_00 , (4,) ).long().to(snake_case__ ) for _ in range(4 )] # train with a DDPM scheduler UpperCAmelCase , UpperCAmelCase = self.get_model_optimizer(resolution=32 ) model.train().to(snake_case__ ) for i in range(4 ): optimizer.zero_grad() UpperCAmelCase = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) UpperCAmelCase = model(snake_case__ , timesteps[i] ).sample UpperCAmelCase = torch.nn.functional.mse_loss(snake_case__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM UpperCAmelCase , UpperCAmelCase = self.get_model_optimizer(resolution=32 ) model.train().to(snake_case__ ) for i in range(4 ): optimizer.zero_grad() UpperCAmelCase = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) UpperCAmelCase = model(snake_case__ , timesteps[i] ).sample UpperCAmelCase = torch.nn.functional.mse_loss(snake_case__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-5 ) )
673
0
'''simple docstring''' import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class a__ ( a_ , unittest.TestCase ): lowerCamelCase : str =VideoToVideoSDPipeline lowerCamelCase : List[str] =TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {'image', 'width', 'height'} lowerCamelCase : int =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {'image'} lowerCamelCase : int =PipelineTesterMixin.required_optional_params - {'latents'} lowerCamelCase : List[str] =False # No `output_type`. lowerCamelCase : Any =frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" torch.manual_seed(0 ) __lowerCamelCase = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , ) __lowerCamelCase = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , clip_sample=snake_case__ , set_alpha_to_one=snake_case__ , ) torch.manual_seed(0 ) __lowerCamelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) __lowerCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act='''gelu''' , projection_dim=5_12 , ) __lowerCamelCase = CLIPTextModel(snake_case__ ) __lowerCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __lowerCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Union[str, Any] , a : Tuple=0 ): """simple docstring""" __lowerCamelCase = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) if str(snake_case__ ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(snake_case__ ) else: __lowerCamelCase = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) __lowerCamelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''video''': video, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = VideoToVideoSDPipeline(**snake_case__ ) __lowerCamelCase = sd_pipe.to(snake_case__ ) sd_pipe.set_progress_bar_config(disable=snake_case__ ) __lowerCamelCase = self.get_dummy_inputs(snake_case__ ) __lowerCamelCase = '''np''' __lowerCamelCase = sd_pipe(**snake_case__ ).frames __lowerCamelCase = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) __lowerCamelCase = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=snake_case__ , expected_max_diff=5e-3 ) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" pass def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" return super().test_progress_bar() @slow @skip_mps class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL''' , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames __lowerCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) __lowerCamelCase = torch.randn((1, 10, 3, 10_24, 5_76) , generator=snake_case__ ) __lowerCamelCase = video.to('''cuda''' ) __lowerCamelCase = '''Spiderman is surfing''' __lowerCamelCase = pipe(snake_case__ , video=snake_case__ , generator=snake_case__ , num_inference_steps=3 , output_type='''pt''' ).frames __lowerCamelCase = np.array([-1.0_45_89_84, -1.1_27_92_97, -0.9_66_30_86, -0.91_50_39_06, -0.75_09_76_56] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
546
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class UpperCamelCase_ : def __init__( self , snake_case__=2 , snake_case__=3 , snake_case__=64 , snake_case__=None ) -> List[str]: """simple docstring""" UpperCAmelCase = np.random.default_rng(snake_case__ ) UpperCAmelCase = length UpperCAmelCase = rng.normal(size=(length,) ).astype(np.floataa ) UpperCAmelCase = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> int: """simple docstring""" return self.length def __getitem__( self , snake_case__ ) -> Tuple: """simple docstring""" return {"x": self.x[i], "y": self.y[i]} class UpperCamelCase_ ( torch.nn.Module ): def __init__( self , snake_case__=0 , snake_case__=0 , snake_case__=False ) -> List[str]: """simple docstring""" super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = True def UpperCamelCase_ ( self , snake_case__=None ) -> List[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCAmelCase = False return x * self.a[0] + self.b[0] class UpperCamelCase_ ( torch.nn.Module ): def __init__( self , snake_case__=0 , snake_case__=0 , snake_case__=False ) -> List[Any]: """simple docstring""" super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor(snake_case__ ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor(snake_case__ ).float() ) UpperCAmelCase = True def UpperCamelCase_ ( self , snake_case__=None ) -> Optional[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCAmelCase = False return x * self.a + self.b def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase = 16 ): '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer UpperCAmelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCAmelCase = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} UpperCAmelCase = load_dataset("""csv""" , data_files=lowerCAmelCase ) UpperCAmelCase = datasets["""train"""].unique("""label""" ) UpperCAmelCase = {v: i for i, v in enumerate(lowerCAmelCase )} def tokenize_function(lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase , max_length=lowerCAmelCase , padding="""max_length""" ) if "label" in examples: UpperCAmelCase = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase = datasets.map( lowerCAmelCase , batched=lowerCAmelCase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowerCAmelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCAmelCase = DataLoader(tokenized_datasets["""train"""] , shuffle=lowerCAmelCase , collate_fn=lowerCAmelCase , batch_size=2 ) UpperCAmelCase = DataLoader(tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase , collate_fn=lowerCAmelCase , batch_size=1 ) return train_dataloader, eval_dataloader
673
0
import argparse import os from accelerate.test_utils import execute_subprocess_async def a_ ( SCREAMING_SNAKE_CASE__ : Optional[int]=None ): '''simple docstring''' if subparsers is not None: _lowerCamelCase : Optional[Any] =subparsers.add_parser('test' ) else: _lowerCamelCase : Any =argparse.ArgumentParser('Accelerate test command' ) parser.add_argument( '--config_file' , default=SCREAMING_SNAKE_CASE__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) return parser def a_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' _lowerCamelCase : List[Any] =os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['test_utils', 'scripts', 'test_script.py'] ) if args.config_file is None: _lowerCamelCase : Any =script_name else: _lowerCamelCase : Optional[int] =F'''--config_file={args.config_file} {script_name}''' _lowerCamelCase : List[Any] =['accelerate-launch'] + test_args.split() _lowerCamelCase : Any =execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=os.environ.copy() ) if result.returncode == 0: print('Test is a success! You are ready for your distributed training!' ) def a_ ( ): '''simple docstring''' _lowerCamelCase : Union[str, Any] =test_command_parser() _lowerCamelCase : int =parser.parse_args() test_command(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
464
"""simple docstring""" import flax.linen as nn import jax import jax.numpy as jnp class UpperCamelCase_ ( nn.Module ): _A : int _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , snake_case__ ) -> Tuple: """simple docstring""" UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = hidden_states.shape UpperCAmelCase = jax.image.resize( snake_case__ , shape=(batch, height * 2, width * 2, channels) , method="""nearest""" , ) UpperCAmelCase = self.conv(snake_case__ ) return hidden_states class UpperCamelCase_ ( nn.Module ): _A : int _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , snake_case__ ) -> Any: """simple docstring""" UpperCAmelCase = self.conv(snake_case__ ) return hidden_states class UpperCamelCase_ ( nn.Module ): _A : int _A : int = None _A : float = 0.0 _A : bool = None _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.in_channels if self.out_channels is None else self.out_channels UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = nn.Dense(snake_case__ , dtype=self.dtype ) UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Dropout(self.dropout_prob ) UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut UpperCAmelCase = None if use_nin_shortcut: UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(1, 1) , strides=(1, 1) , padding="""VALID""" , dtype=self.dtype , ) def __call__( self , snake_case__ , snake_case__ , snake_case__=True ) -> List[Any]: """simple docstring""" UpperCAmelCase = hidden_states UpperCAmelCase = self.norma(snake_case__ ) UpperCAmelCase = nn.swish(snake_case__ ) UpperCAmelCase = self.conva(snake_case__ ) UpperCAmelCase = self.time_emb_proj(nn.swish(snake_case__ ) ) UpperCAmelCase = jnp.expand_dims(jnp.expand_dims(snake_case__ , 1 ) , 1 ) UpperCAmelCase = hidden_states + temb UpperCAmelCase = self.norma(snake_case__ ) UpperCAmelCase = nn.swish(snake_case__ ) UpperCAmelCase = self.dropout(snake_case__ , snake_case__ ) UpperCAmelCase = self.conva(snake_case__ ) if self.conv_shortcut is not None: UpperCAmelCase = self.conv_shortcut(snake_case__ ) return hidden_states + residual
673
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : List[str] = { '''configuration_luke''': ['''LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LukeConfig'''], '''tokenization_luke''': ['''LukeTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = [ '''LUKE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LukeForEntityClassification''', '''LukeForEntityPairClassification''', '''LukeForEntitySpanClassification''', '''LukeForMultipleChoice''', '''LukeForQuestionAnswering''', '''LukeForSequenceClassification''', '''LukeForTokenClassification''', '''LukeForMaskedLM''', '''LukeModel''', '''LukePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
567
"""simple docstring""" from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=13 , snake_case__=30 , snake_case__=2 , snake_case__=3 , snake_case__=True , snake_case__=True , snake_case__=32 , snake_case__=2 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=10 , snake_case__=0.02 , snake_case__=3 , snake_case__=None , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase = (image_size // patch_size) ** 2 UpperCAmelCase = num_patches + 1 def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" return ViTConfig( 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=snake_case__ , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = TFViTModel(config=snake_case__ ) UpperCAmelCase = model(snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase = self.image_size // 2 UpperCAmelCase = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) UpperCAmelCase = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.type_sequence_label_size UpperCAmelCase = TFViTForImageClassification(snake_case__ ) UpperCAmelCase = model(snake_case__ , labels=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase = self.image_size // 2 UpperCAmelCase = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase = 1 UpperCAmelCase = TFViTForImageClassification(snake_case__ ) UpperCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase = model(snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Optional[int] = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () _A : Optional[Any] = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) _A : Optional[int] = False _A : Any = False _A : List[str] = False def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = TFViTModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=37 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , tf.keras.layers.Layer ) ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) UpperCAmelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case__ ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) @slow def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(snake_case__ ) def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCamelCase_ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=snake_case__ , return_tensors="""tf""" ) # forward pass UpperCAmelCase = model(**snake_case__ ) # verify the logits UpperCAmelCase = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , snake_case__ ) UpperCAmelCase = tf.constant([-0.2_744, 0.8_215, -0.0_836] ) tf.debugging.assert_near(outputs.logits[0, :3] , snake_case__ , atol=1e-4 )
673
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[str]=7 , lowerCAmelCase__ : List[str]=3 , lowerCAmelCase__ : Dict=1_8 , lowerCAmelCase__ : Dict=3_0 , lowerCAmelCase__ : Optional[Any]=4_0_0 , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : str=None , lowerCAmelCase__ : Union[str, Any]=True , lowerCAmelCase__ : Dict=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"""shortest_edge""": 2_0} __SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"""height""": 1_8, """width""": 1_8} __SCREAMING_SNAKE_CASE : Any = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : List[Any] = num_channels __SCREAMING_SNAKE_CASE : Optional[int] = image_size __SCREAMING_SNAKE_CASE : List[Any] = min_resolution __SCREAMING_SNAKE_CASE : List[Any] = max_resolution __SCREAMING_SNAKE_CASE : List[Any] = do_resize __SCREAMING_SNAKE_CASE : Tuple = size __SCREAMING_SNAKE_CASE : Optional[Any] = do_center_crop __SCREAMING_SNAKE_CASE : Dict = crop_size def UpperCamelCase__ ( self : Any ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class _UpperCamelCase ( a_ , unittest.TestCase ): '''simple docstring''' _A : Tuple = MobileNetVaImageProcessor if is_vision_available() else None def UpperCamelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = MobileNetVaImageProcessingTester(self ) @property def UpperCamelCase__ ( self : List[str] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case__ , """do_resize""" ) ) self.assertTrue(hasattr(snake_case__ , """size""" ) ) self.assertTrue(hasattr(snake_case__ , """do_center_crop""" ) ) self.assertTrue(hasattr(snake_case__ , """crop_size""" ) ) def UpperCamelCase__ ( self : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 2_0} ) self.assertEqual(image_processor.crop_size , {"""height""": 1_8, """width""": 1_8} ) __SCREAMING_SNAKE_CASE : int = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 4_2} ) self.assertEqual(image_processor.crop_size , {"""height""": 8_4, """width""": 8_4} ) def UpperCamelCase__ ( self : str ): """simple docstring""" pass def UpperCamelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = 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=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched __SCREAMING_SNAKE_CASE : str = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def UpperCamelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , numpify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , np.ndarray ) # 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched __SCREAMING_SNAKE_CASE : int = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def UpperCamelCase__ ( self : int ): """simple docstring""" __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=snake_case__ , torchify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched __SCREAMING_SNAKE_CASE : int = image_processing(snake_case__ , 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"""], ) , )
578
"""simple docstring""" import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=13 , snake_case__=7 , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=99 , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=5_12 , snake_case__=16 , snake_case__=2 , snake_case__=0.02 , snake_case__=3 , snake_case__=4 , snake_case__=None , ) -> int: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case__ , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> List[str]: """simple docstring""" UpperCAmelCase = NystromformerModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ ) UpperCAmelCase = model(snake_case__ , token_type_ids=snake_case__ ) UpperCAmelCase = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = NystromformerForMaskedLM(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = NystromformerForQuestionAnswering(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = NystromformerForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = NystromformerForTokenClassification(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = self.num_choices UpperCAmelCase = NystromformerForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Optional[Any] = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) _A : Optional[Any] = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) _A : int = False _A : Dict = False def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = NystromformerModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=snake_case__ , hidden_size=37 ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase = type self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case__ ) def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case__ ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case__ ) def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case__ ) @slow def UpperCamelCase_ ( self ) -> int: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = NystromformerModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): UpperCAmelCase = model(snake_case__ )[0] UpperCAmelCase = torch.Size((1, 6, 7_68) ) self.assertEqual(output.shape , snake_case__ ) UpperCAmelCase = torch.tensor( [[[-0.4_532, -0.0_936, 0.5_137], [-0.2_676, 0.0_628, 0.6_186], [-0.3_629, -0.1_726, 0.4_716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) ) @slow def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = """the [MASK] of Belgium is Brussels""" UpperCAmelCase = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = tokenizer(snake_case__ , return_tensors="""pt""" ) with torch.no_grad(): UpperCAmelCase = model(encoding.input_ids ).logits UpperCAmelCase = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(snake_case__ ) , """capital""" )
673
0
"""simple docstring""" import math def __lowercase ( _a ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_a ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __lowercase ( _a = 10_001 ): try: snake_case_ : str = int(_a ) except (TypeError, ValueError): raise TypeError('''Parameter nth must be int or castable to int.''' ) from None if nth <= 0: raise ValueError('''Parameter nth must be greater than or equal to one.''' ) snake_case_ : Any = [] snake_case_ : Union[str, Any] = 2 while len(_a ) < nth: if is_prime(_a ): primes.append(_a ) num += 1 else: num += 1 return primes[len(_a ) - 1] if __name__ == "__main__": print(f'{solution() = }')
123
"""simple docstring""" import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Optional[int] = False def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' return TrainCommand(lowerCAmelCase ) class UpperCamelCase_ ( a_ ): @staticmethod def UpperCamelCase_ ( snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = parser.add_parser("""train""" , help="""CLI tool to train a model on a task.""" ) train_parser.add_argument( """--train_data""" , type=snake_case__ , required=snake_case__ , help="""path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.""" , ) train_parser.add_argument( """--column_label""" , type=snake_case__ , default=0 , help="""Column of the dataset csv file with example labels.""" ) train_parser.add_argument( """--column_text""" , type=snake_case__ , default=1 , help="""Column of the dataset csv file with example texts.""" ) train_parser.add_argument( """--column_id""" , type=snake_case__ , default=2 , help="""Column of the dataset csv file with example ids.""" ) train_parser.add_argument( """--skip_first_row""" , action="""store_true""" , help="""Skip the first row of the csv file (headers).""" ) train_parser.add_argument("""--validation_data""" , type=snake_case__ , default="""""" , help="""path to validation dataset.""" ) train_parser.add_argument( """--validation_split""" , type=snake_case__ , default=0.1 , help="""if validation dataset is not provided, fraction of train dataset to use as validation dataset.""" , ) train_parser.add_argument("""--output""" , type=snake_case__ , default="""./""" , help="""path to saved the trained model.""" ) train_parser.add_argument( """--task""" , type=snake_case__ , default="""text_classification""" , help="""Task to train the model on.""" ) train_parser.add_argument( """--model""" , type=snake_case__ , default="""bert-base-uncased""" , help="""Model's name or path to stored model.""" ) train_parser.add_argument("""--train_batch_size""" , type=snake_case__ , default=32 , help="""Batch size for training.""" ) train_parser.add_argument("""--valid_batch_size""" , type=snake_case__ , default=64 , help="""Batch size for validation.""" ) train_parser.add_argument("""--learning_rate""" , type=snake_case__ , default=3e-5 , help="""Learning rate.""" ) train_parser.add_argument("""--adam_epsilon""" , type=snake_case__ , default=1e-08 , help="""Epsilon for Adam optimizer.""" ) train_parser.set_defaults(func=snake_case__ ) def __init__( self , snake_case__ ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = logging.get_logger("""transformers-cli/training""" ) UpperCAmelCase = """tf""" if is_tf_available() else """torch""" os.makedirs(args.output , exist_ok=snake_case__ ) UpperCAmelCase = args.output UpperCAmelCase = args.column_label UpperCAmelCase = args.column_text UpperCAmelCase = args.column_id self.logger.info(f'''Loading {args.task} pipeline for {args.model}''' ) if args.task == "text_classification": UpperCAmelCase = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'''Loading dataset from {args.train_data}''' ) UpperCAmelCase = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) UpperCAmelCase = None if args.validation_data: self.logger.info(f'''Loading validation dataset from {args.validation_data}''' ) UpperCAmelCase = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) UpperCAmelCase = args.validation_split UpperCAmelCase = args.train_batch_size UpperCAmelCase = args.valid_batch_size UpperCAmelCase = args.learning_rate UpperCAmelCase = args.adam_epsilon def UpperCamelCase_ ( self ) -> Any: """simple docstring""" if self.framework == "tf": return self.run_tf() return self.run_torch() def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" raise NotImplementedError def UpperCamelCase_ ( self ) -> str: """simple docstring""" self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
673
0
'''simple docstring''' from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCamelCase : '''simple docstring''' def __init__( self , a__ , a__=13 , a__=30 , a__=2 , a__=3 , a__=True , a__=True , a__=32 , a__=2 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.02 , a__=3 , a__=None , ): __SCREAMING_SNAKE_CASE : int = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : str = image_size __SCREAMING_SNAKE_CASE : Tuple = patch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = is_training __SCREAMING_SNAKE_CASE : Tuple = use_labels __SCREAMING_SNAKE_CASE : int = hidden_size __SCREAMING_SNAKE_CASE : Any = num_hidden_layers __SCREAMING_SNAKE_CASE : Dict = num_attention_heads __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE : List[Any] = initializer_range __SCREAMING_SNAKE_CASE : Optional[Any] = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE : Any = (image_size // patch_size) ** 2 __SCREAMING_SNAKE_CASE : Optional[int] = num_patches + 1 def a_ ( self ): __SCREAMING_SNAKE_CASE : Optional[Any] = 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 : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, pixel_values, labels def a_ ( self ): return ViTConfig( 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=snake_case__ , initializer_range=self.initializer_range , ) def a_ ( self , a__ , a__ , a__ ): __SCREAMING_SNAKE_CASE : str = TFViTModel(config=snake_case__ ) __SCREAMING_SNAKE_CASE : int = model(snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. __SCREAMING_SNAKE_CASE : Optional[int] = self.image_size // 2 __SCREAMING_SNAKE_CASE : Optional[int] = pixel_values[:, :, :image_size, :image_size] __SCREAMING_SNAKE_CASE : Any = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def a_ ( self , a__ , a__ , a__ ): __SCREAMING_SNAKE_CASE : List[str] = self.type_sequence_label_size __SCREAMING_SNAKE_CASE : Dict = TFViTForImageClassification(snake_case__ ) __SCREAMING_SNAKE_CASE : Any = model(snake_case__ , labels=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. __SCREAMING_SNAKE_CASE : Optional[int] = self.image_size // 2 __SCREAMING_SNAKE_CASE : Dict = pixel_values[:, :, :image_size, :image_size] __SCREAMING_SNAKE_CASE : Tuple = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) 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 : Union[str, Any] = TFViTForImageClassification(snake_case__ ) __SCREAMING_SNAKE_CASE : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : str = model(snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( self ): __SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs __SCREAMING_SNAKE_CASE : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class __lowerCamelCase ( a_ , a_ , unittest.TestCase ): '''simple docstring''' snake_case__ : Optional[int] = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () snake_case__ : Optional[Any] = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) snake_case__ : Optional[int] = False snake_case__ : Any = False snake_case__ : List[str] = False def a_ ( self ): __SCREAMING_SNAKE_CASE : Optional[int] = TFViTModelTester(self ) __SCREAMING_SNAKE_CASE : List[str] = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=37 ) def a_ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a_ ( self ): pass @unittest.skip(reason="ViT does not use inputs_embeds" ) def a_ ( self ): pass def a_ ( self ): __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 : Any = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) __SCREAMING_SNAKE_CASE : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , tf.keras.layers.Layer ) ) def a_ ( self ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = 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(snake_case__ ) __SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : str = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case__ ) def a_ ( self ): __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def a_ ( self ): __SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) @slow def a_ ( self ): __SCREAMING_SNAKE_CASE : Any = TFViTModel.from_pretrained("google/vit-base-patch16-224" ) self.assertIsNotNone(snake_case__ ) def __A ( ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def a_ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a_ ( self ): __SCREAMING_SNAKE_CASE : str = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ) __SCREAMING_SNAKE_CASE : List[Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : List[Any] = prepare_img() __SCREAMING_SNAKE_CASE : Dict = image_processor(images=snake_case__ , return_tensors="tf" ) # forward pass __SCREAMING_SNAKE_CASE : Tuple = model(**snake_case__ ) # verify the logits __SCREAMING_SNAKE_CASE : List[str] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , snake_case__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = tf.constant([-0.2744, 0.8215, -0.0836] ) tf.debugging.assert_near(outputs.logits[0, :3] , snake_case__ , atol=1e-4 )
211
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=sys.maxsize ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = """bilinear""" UpperCAmelCase = max_size UpperCAmelCase = short_edge_length def __call__( self , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = [] for img in imgs: UpperCAmelCase , UpperCAmelCase = img.shape[:2] # later: provide list and randomly choose index for resize UpperCAmelCase = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img UpperCAmelCase = size * 1.0 / min(snake_case__ , snake_case__ ) if h < w: UpperCAmelCase , UpperCAmelCase = size, scale * w else: UpperCAmelCase , UpperCAmelCase = scale * h, size if max(snake_case__ , snake_case__ ) > self.max_size: UpperCAmelCase = self.max_size * 1.0 / max(snake_case__ , snake_case__ ) UpperCAmelCase = newh * scale UpperCAmelCase = neww * scale UpperCAmelCase = int(neww + 0.5 ) UpperCAmelCase = int(newh + 0.5 ) if img.dtype == np.uinta: UpperCAmelCase = Image.fromarray(snake_case__ ) UpperCAmelCase = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) UpperCAmelCase = np.asarray(snake_case__ ) else: UpperCAmelCase = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw UpperCAmelCase = nn.functional.interpolate( snake_case__ , (newh, neww) , mode=self.interp_method , align_corners=snake_case__ ).squeeze(0 ) img_augs.append(snake_case__ ) return img_augs class UpperCamelCase_ : def __init__( self , snake_case__ ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) UpperCAmelCase = cfg.INPUT.FORMAT UpperCAmelCase = cfg.SIZE_DIVISIBILITY UpperCAmelCase = cfg.PAD_VALUE UpperCAmelCase = cfg.INPUT.MAX_SIZE_TEST UpperCAmelCase = cfg.MODEL.DEVICE UpperCAmelCase = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) UpperCAmelCase = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) UpperCAmelCase = lambda snake_case__ : (x - self.pixel_mean) / self.pixel_std def UpperCamelCase_ ( self , snake_case__ ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = tuple(max(snake_case__ ) for s in zip(*[img.shape for img in images] ) ) UpperCAmelCase = [im.shape[-2:] for im in images] UpperCAmelCase = [ nn.functional.pad( snake_case__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(snake_case__ , snake_case__ ) ] return torch.stack(snake_case__ ), torch.tensor(snake_case__ ) def __call__( self , snake_case__ , snake_case__=False ) -> Optional[Any]: """simple docstring""" with torch.no_grad(): if not isinstance(snake_case__ , snake_case__ ): UpperCAmelCase = [images] if single_image: assert len(snake_case__ ) == 1 for i in range(len(snake_case__ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(snake_case__ , images.pop(snake_case__ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( snake_case__ , torch.as_tensor(img_tensorize(images.pop(snake_case__ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge UpperCAmelCase = torch.tensor([im.shape[:2] for im in images] ) UpperCAmelCase = self.aug(snake_case__ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic UpperCAmelCase = [self.normalizer(snake_case__ ) for x in images] # now pad them to do the following operations UpperCAmelCase , UpperCAmelCase = self.pad(snake_case__ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad UpperCAmelCase = torch.true_divide(snake_case__ , snake_case__ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' assert torch.isfinite(lowerCAmelCase ).all(), "Box tensor contains infinite or NaN!" UpperCAmelCase , UpperCAmelCase = box_size tensor[:, 0].clamp_(min=0 , max=lowerCAmelCase ) tensor[:, 1].clamp_(min=0 , max=lowerCAmelCase ) tensor[:, 2].clamp_(min=0 , max=lowerCAmelCase ) tensor[:, 3].clamp_(min=0 , max=lowerCAmelCase )
673
0
'''simple docstring''' from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging __a: int = logging.get_logger(__name__) def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): try: with open(UpperCAmelCase , '''rb''' ) as flax_state_f: lowercase__ : List[str] = from_bytes(UpperCAmelCase , flax_state_f.read() ) except UnpicklingError as e: try: with open(UpperCAmelCase ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F"""Unable to convert {model_file} to Flax deserializable object. """ ) return load_flax_weights_in_pytorch_model(UpperCAmelCase , UpperCAmelCase ) def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights lowercase__ : str = flatten_dict(jax.tree_util.tree_map(lambda UpperCAmelCase : x.dtype == jnp.bfloataa , UpperCAmelCase ) ).values() if any(UpperCAmelCase ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) lowercase__ : Union[str, Any] = jax.tree_util.tree_map( lambda UpperCAmelCase : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , UpperCAmelCase ) lowercase__ : Optional[Any] = '''''' lowercase__ : int = flatten_dict(UpperCAmelCase , sep='''.''' ) lowercase__ : Tuple = pt_model.state_dict() # keep track of unexpected & missing keys lowercase__ : Optional[int] = [] lowercase__ : int = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): lowercase__ : List[Any] = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: lowercase__ : Union[str, Any] = flax_key_tuple_array[:-1] + ['''weight'''] lowercase__ : Any = jnp.transpose(UpperCAmelCase , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": lowercase__ : int = flax_key_tuple_array[:-1] + ['''weight'''] lowercase__ : Tuple = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": lowercase__ : List[str] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(UpperCAmelCase ): lowercase__ : Any = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) lowercase__ : Any = '''.'''.join(UpperCAmelCase ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F"""Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected """ F"""to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) else: # add weight to pytorch dict lowercase__ : List[Any] = np.asarray(UpperCAmelCase ) if not isinstance(UpperCAmelCase , np.ndarray ) else flax_tensor lowercase__ : Optional[int] = torch.from_numpy(UpperCAmelCase ) # remove from missing keys missing_keys.remove(UpperCAmelCase ) else: # weight is not expected by PyTorch model unexpected_keys.append(UpperCAmelCase ) pt_model.load_state_dict(UpperCAmelCase ) # re-transform missing_keys to list lowercase__ : Union[str, Any] = list(UpperCAmelCase ) if len(UpperCAmelCase ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' F""" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing""" F""" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture""" ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' F""" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect""" ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(UpperCAmelCase ) > 0: logger.warning( F"""Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly""" F""" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to""" ''' use it for predictions and inference.''' ) return pt_model
152
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ : List[str] = logging.get_logger(__name__) def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase=False ): '''simple docstring''' UpperCAmelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''deit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''deit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''deit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''deit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''deit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''deit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''deit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''deit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''deit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''deit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" UpperCAmelCase = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: UpperCAmelCase = """""" else: UpperCAmelCase = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) UpperCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[ : config.hidden_size, : ] UpperCAmelCase = in_proj_bias[: config.hidden_size] UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = dct.pop(lowerCAmelCase ) UpperCAmelCase = val def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCAmelCase = Image.open(requests.get(lowerCAmelCase , stream=lowerCAmelCase ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = DeiTConfig() # all deit models have fine-tuned heads UpperCAmelCase = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size UpperCAmelCase = 1000 UpperCAmelCase = """huggingface/label-files""" UpperCAmelCase = """imagenet-1k-id2label.json""" UpperCAmelCase = json.load(open(hf_hub_download(lowerCAmelCase , lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) UpperCAmelCase = {int(lowerCAmelCase ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} UpperCAmelCase = int(deit_name[-6:-4] ) UpperCAmelCase = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): UpperCAmelCase = 192 UpperCAmelCase = 768 UpperCAmelCase = 12 UpperCAmelCase = 3 elif deit_name[9:].startswith("""small""" ): UpperCAmelCase = 384 UpperCAmelCase = 1536 UpperCAmelCase = 12 UpperCAmelCase = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): UpperCAmelCase = 1024 UpperCAmelCase = 4096 UpperCAmelCase = 24 UpperCAmelCase = 16 # load original model from timm UpperCAmelCase = timm.create_model(lowerCAmelCase , pretrained=lowerCAmelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys UpperCAmelCase = timm_model.state_dict() UpperCAmelCase = create_rename_keys(lowerCAmelCase , lowerCAmelCase ) for src, dest in rename_keys: rename_key(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) read_in_q_k_v(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # load HuggingFace model UpperCAmelCase = DeiTForImageClassificationWithTeacher(lowerCAmelCase ).eval() model.load_state_dict(lowerCAmelCase ) # Check outputs on an image, prepared by DeiTImageProcessor UpperCAmelCase = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 UpperCAmelCase = DeiTImageProcessor(size=lowerCAmelCase , crop_size=config.image_size ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors="""pt""" ) UpperCAmelCase = encoding["""pixel_values"""] UpperCAmelCase = model(lowerCAmelCase ) UpperCAmelCase = timm_model(lowerCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase , outputs.logits , atol=1e-3 ) Path(lowerCAmelCase ).mkdir(exist_ok=lowerCAmelCase ) print(F'''Saving model {deit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCAmelCase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowerCAmelCase ) if __name__ == "__main__": lowerCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) lowerCAmelCase_ : str = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
673
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer __lowercase : Optional[int] = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast __lowercase : int = TaTokenizerFast __lowercase : Optional[int] = {'''configuration_mt5''': ['''MT5Config''', '''MT5OnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Tuple = [ '''MT5EncoderModel''', '''MT5ForConditionalGeneration''', '''MT5ForQuestionAnswering''', '''MT5Model''', '''MT5PreTrainedModel''', '''MT5Stack''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Union[str, Any] = ['''TFMT5EncoderModel''', '''TFMT5ForConditionalGeneration''', '''TFMT5Model'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ['''FlaxMT5EncoderModel''', '''FlaxMT5ForConditionalGeneration''', '''FlaxMT5Model'''] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys __lowercase : Any = _LazyModule( __name__, globals()['__file__'], _import_structure, extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast}, module_spec=__spec__, )
476
"""simple docstring""" import unittest from typing import Dict, List, Optional, Union 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 BridgeTowerImageProcessor class UpperCamelCase_ ( unittest.TestCase ): def __init__( self , snake_case__ , snake_case__ = True , snake_case__ = None , snake_case__ = 32 , snake_case__ = True , snake_case__ = 1 / 2_55 , snake_case__ = True , snake_case__ = True , snake_case__ = [0.48_145_466, 0.4_578_275, 0.40_821_073] , snake_case__ = [0.26_862_954, 0.26_130_258, 0.27_577_711] , snake_case__ = True , snake_case__=7 , snake_case__=30 , snake_case__=4_00 , snake_case__=3 , ) -> List[str]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = do_resize UpperCAmelCase = size if size is not None else {"""shortest_edge""": 2_88} UpperCAmelCase = size_divisor UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = do_normalize UpperCAmelCase = do_center_crop UpperCAmelCase = image_mean UpperCAmelCase = image_std UpperCAmelCase = do_pad UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def UpperCamelCase_ ( self , snake_case__ , snake_case__=False ) -> int: """simple docstring""" if not batched: UpperCAmelCase = self.size["""shortest_edge"""] UpperCAmelCase = image_inputs[0] if isinstance(snake_case__ , Image.Image ): UpperCAmelCase , UpperCAmelCase = image.size else: UpperCAmelCase , UpperCAmelCase = image.shape[1], image.shape[2] UpperCAmelCase = size / min(snake_case__ , snake_case__ ) if h < w: UpperCAmelCase , UpperCAmelCase = size, scale * w else: UpperCAmelCase , UpperCAmelCase = scale * h, size UpperCAmelCase = int((13_33 / 8_00) * size ) if max(snake_case__ , snake_case__ ) > max_size: UpperCAmelCase = max_size / max(snake_case__ , snake_case__ ) UpperCAmelCase = newh * scale UpperCAmelCase = neww * scale UpperCAmelCase , UpperCAmelCase = int(newh + 0.5 ), int(neww + 0.5 ) UpperCAmelCase , UpperCAmelCase = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: UpperCAmelCase = [] for image in image_inputs: UpperCAmelCase , UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCAmelCase = max(snake_case__ , key=lambda snake_case__ : item[0] )[0] UpperCAmelCase = max(snake_case__ , key=lambda snake_case__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : List[Any] = BridgeTowerImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = BridgeTowerImageProcessingTester(self ) @property def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case__ , """image_mean""" ) ) self.assertTrue(hasattr(snake_case__ , """image_std""" ) ) self.assertTrue(hasattr(snake_case__ , """do_normalize""" ) ) self.assertTrue(hasattr(snake_case__ , """do_resize""" ) ) self.assertTrue(hasattr(snake_case__ , """size""" ) ) self.assertTrue(hasattr(snake_case__ , """size_divisor""" ) ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , Image.Image ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , numpify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , np.ndarray ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , torchify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , torch.Tensor ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
673
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase=False )-> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ('''cls_token''', '''vit.embeddings.cls_token'''), ('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE_ = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase=False )-> str: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE_ = '''''' else: SCREAMING_SNAKE_CASE_ = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE_ = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE_ = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE_ = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE_ = in_proj_bias[-config.hidden_size :] def UpperCAmelCase ( UpperCAmelCase )-> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(UpperCAmelCase ,UpperCAmelCase ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase )-> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_ = dct.pop(UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = val def UpperCAmelCase ( )-> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = Image.open(requests.get(UpperCAmelCase ,stream=UpperCAmelCase ).raw ) return im @torch.no_grad() def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase )-> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_ = ViTConfig() SCREAMING_SNAKE_CASE_ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = int(vit_name[-12:-10] ) SCREAMING_SNAKE_CASE_ = int(vit_name[-9:-6] ) else: SCREAMING_SNAKE_CASE_ = 1000 SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(UpperCAmelCase ,UpperCAmelCase ,repo_type='''dataset''' ) ,'''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(UpperCAmelCase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = idalabel SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = int(vit_name[-6:-4] ) SCREAMING_SNAKE_CASE_ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith('''tiny''' ): SCREAMING_SNAKE_CASE_ = 192 SCREAMING_SNAKE_CASE_ = 768 SCREAMING_SNAKE_CASE_ = 12 SCREAMING_SNAKE_CASE_ = 3 elif vit_name[9:].startswith('''small''' ): SCREAMING_SNAKE_CASE_ = 384 SCREAMING_SNAKE_CASE_ = 1536 SCREAMING_SNAKE_CASE_ = 12 SCREAMING_SNAKE_CASE_ = 6 else: pass else: if vit_name[4:].startswith('''small''' ): SCREAMING_SNAKE_CASE_ = 768 SCREAMING_SNAKE_CASE_ = 2304 SCREAMING_SNAKE_CASE_ = 8 SCREAMING_SNAKE_CASE_ = 8 elif vit_name[4:].startswith('''base''' ): pass elif vit_name[4:].startswith('''large''' ): SCREAMING_SNAKE_CASE_ = 1024 SCREAMING_SNAKE_CASE_ = 4096 SCREAMING_SNAKE_CASE_ = 24 SCREAMING_SNAKE_CASE_ = 16 elif vit_name[4:].startswith('''huge''' ): SCREAMING_SNAKE_CASE_ = 1280 SCREAMING_SNAKE_CASE_ = 5120 SCREAMING_SNAKE_CASE_ = 32 SCREAMING_SNAKE_CASE_ = 16 # load original model from timm SCREAMING_SNAKE_CASE_ = timm.create_model(UpperCAmelCase ,pretrained=UpperCAmelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE_ = timm_model.state_dict() if base_model: remove_classification_head_(UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = create_rename_keys(UpperCAmelCase ,UpperCAmelCase ) for src, dest in rename_keys: rename_key(UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ) read_in_q_k_v(UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ) # load HuggingFace model if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE_ = ViTModel(UpperCAmelCase ).eval() else: SCREAMING_SNAKE_CASE_ = ViTForImageClassification(UpperCAmelCase ).eval() model.load_state_dict(UpperCAmelCase ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: SCREAMING_SNAKE_CASE_ = DeiTImageProcessor(size=config.image_size ) else: SCREAMING_SNAKE_CASE_ = ViTImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_ = image_processor(images=prepare_img() ,return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = encoding['''pixel_values'''] SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase ) if base_model: SCREAMING_SNAKE_CASE_ = timm_model.forward_features(UpperCAmelCase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(UpperCAmelCase ,outputs.pooler_output ,atol=1E-3 ) else: SCREAMING_SNAKE_CASE_ = timm_model(UpperCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase ,outputs.logits ,atol=1E-3 ) Path(UpperCAmelCase ).mkdir(exist_ok=UpperCAmelCase ) print(f'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCAmelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCAmelCase ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_patch16_224", type=str, help="Name of the ViT timm model you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) A_ = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
393
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : Any = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : List[str] = XLMRobertaTokenizer _A : List[str] = XLMRobertaTokenizerFast _A : Optional[Any] = True _A : List[str] = True def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XLMRobertaTokenizer(snake_case__ , keep_accents=snake_case__ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = """<pad>""" UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__ ) , snake_case__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__ ) , snake_case__ ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(snake_case__ ) , 10_02 ) def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = XLMRobertaTokenizer(snake_case__ , keep_accents=snake_case__ ) UpperCAmelCase = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(snake_case__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) UpperCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( snake_case__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(snake_case__ ) self.assertListEqual( snake_case__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(snake_case__ ) self.assertListEqual( snake_case__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return UpperCAmelCase = (self.rust_tokenizer_class, """hf-internal-testing/tiny-xlm-roberta""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) UpperCAmelCase = self.tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.save_pretrained(snake_case__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) UpperCAmelCase = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(snake_case__ , snake_case__ ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(snake_case__ ) # Save tokenizer rust, legacy_format=True UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(snake_case__ , legacy_format=snake_case__ ) UpperCAmelCase = tokenizer_p.save_pretrained(snake_case__ ) # Checks it save with the same files self.assertSequenceEqual(snake_case__ , snake_case__ ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) shutil.rmtree(snake_case__ ) # Save tokenizer rust, legacy_format=False UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(snake_case__ , legacy_format=snake_case__ ) UpperCAmelCase = tokenizer_p.save_pretrained(snake_case__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) shutil.rmtree(snake_case__ ) @cached_property def UpperCamelCase_ ( self ) -> int: """simple docstring""" return XLMRobertaTokenizer.from_pretrained("""xlm-roberta-base""" ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" with tempfile.NamedTemporaryFile() as f: shutil.copyfile(snake_case__ , f.name ) UpperCAmelCase = XLMRobertaTokenizer(f.name , keep_accents=snake_case__ ) UpperCAmelCase = pickle.dumps(snake_case__ ) pickle.loads(snake_case__ ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" if not self.test_rust_tokenizer: return UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = """I was born in 92000, and this is falsé.""" UpperCAmelCase = tokenizer.tokenize(snake_case__ ) UpperCAmelCase = rust_tokenizer.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) UpperCAmelCase = tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) UpperCAmelCase = rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = tokenizer.encode(snake_case__ ) UpperCAmelCase = rust_tokenizer.encode(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) @slow def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = """Hello World!""" UpperCAmelCase = [0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(snake_case__ , self.big_tokenizer.encode(snake_case__ ) ) @slow def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) UpperCAmelCase = [ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(snake_case__ , self.big_tokenizer.encode(snake_case__ ) ) @slow def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = {"""input_ids""": [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=snake_case__ , model_name="""xlm-roberta-base""" , revision="""d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3""" , )
673
0
__UpperCAmelCase = '''Tobias Carryer''' from time import time class lowerCamelCase : '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=int(time() ) ) -> List[Any]: # noqa: B008 UpperCAmelCase_ : Optional[Any] = multiplier UpperCAmelCase_ : Tuple = increment UpperCAmelCase_ : int = modulo UpperCAmelCase_ : Dict = seed def __UpperCAmelCase ( self ) -> List[Any]: UpperCAmelCase_ : Any = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. __UpperCAmelCase = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31) while True: print(lcg.next_number())
406
"""simple docstring""" import socket def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) UpperCAmelCase = socket.gethostname() UpperCAmelCase = 12312 sock.connect((host, port) ) sock.send(b"""Hello server!""" ) with open("""Received_file""" , """wb""" ) as out_file: print("""File opened""" ) print("""Receiving data...""" ) while True: UpperCAmelCase = sock.recv(1024 ) if not data: break out_file.write(lowerCAmelCase ) print("""Successfully received the file""" ) sock.close() print("""Connection closed""" ) if __name__ == "__main__": main()
673
0
"""simple docstring""" def __a ( A , A ) -> Dict: '''simple docstring''' A__ = 0 A__ = len(A ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None A__ = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(A ): return None A__ = sorted_collection[point] if current_item == item: return point else: if point < left: A__ = left A__ = point elif point > right: A__ = right A__ = point else: if item < current_item: A__ = point - 1 else: A__ = point + 1 return None def __a ( A , A , A , A ) -> Optional[int]: '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None A__ = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(A ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(A , A , A , A ) elif point > right: return interpolation_search_by_recursion(A , A , A , A ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( A , A , A , point - 1 ) else: return interpolation_search_by_recursion( A , A , point + 1 , A ) def __a ( A ) -> Tuple: '''simple docstring''' if collection != sorted(A ): raise ValueError("Collection must be ascending sorted" ) return True if __name__ == "__main__": import sys __UpperCAmelCase =0 if debug == 1: __UpperCAmelCase =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") __UpperCAmelCase =67 __UpperCAmelCase =interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print("""Not found""")
337
"""simple docstring""" import math def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' return math.sqrt(lowerCAmelCase ) * math.sqrt(lowerCAmelCase ) == num def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = 0 UpperCAmelCase = n while left <= right: UpperCAmelCase = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: UpperCAmelCase = mid - 1 else: UpperCAmelCase = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
673
0
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __UpperCAmelCase ={ '''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''' }, } __UpperCAmelCase ={'''allegro/herbert-base-cased''': 5_1_4} __UpperCAmelCase ={} class a__ ( a_ ): lowerCamelCase : Dict =VOCAB_FILES_NAMES lowerCamelCase : Any =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[str] =PRETRAINED_INIT_CONFIGURATION lowerCamelCase : Dict =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Tuple =HerbertTokenizer def __init__( self : Tuple , a : Any=None , a : int=None , a : Union[str, Any]=None , a : Union[str, Any]="<s>" , a : Optional[int]="<unk>" , a : List[Any]="<pad>" , a : Optional[Any]="<mask>" , a : str="</s>" , **a : Optional[Any] , ): """simple docstring""" super().__init__( snake_case__ , snake_case__ , tokenizer_file=snake_case__ , cls_token=snake_case__ , unk_token=snake_case__ , pad_token=snake_case__ , mask_token=snake_case__ , sep_token=snake_case__ , **snake_case__ , ) def SCREAMING_SNAKE_CASE__ ( self : Dict , a : int , a : Union[str, Any] = None ): """simple docstring""" __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [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 SCREAMING_SNAKE_CASE__ ( self : Tuple , a : str , a : List[Any] = None , a : Any = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case__ , token_ids_a=snake_case__ , already_has_special_tokens=snake_case__ ) if token_ids_a is None: return [1] + ([0] * len(snake_case__ )) + [1] return [1] + ([0] * len(snake_case__ )) + [1] + ([0] * len(snake_case__ )) + [1] def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : Tuple , a : str = None ): """simple docstring""" __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Any , a : Tuple = None ): """simple docstring""" __lowerCamelCase = self._tokenizer.model.save(snake_case__ , name=snake_case__ ) return tuple(snake_case__ )
546
"""simple docstring""" import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _lowerCAmelCase ( *lowerCAmelCase ): '''simple docstring''' if not isinstance(lowerCAmelCase , lowerCAmelCase ): UpperCAmelCase = list(lowerCAmelCase ) for i in range(len(lowerCAmelCase ) ): UpperCAmelCase = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(lowerCAmelCase , lowerCAmelCase ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _lowerCAmelCase ( lowerCAmelCase = None , lowerCAmelCase = 128 ): '''simple docstring''' if function is None: return functools.partial(lowerCAmelCase , starting_batch_size=lowerCAmelCase ) UpperCAmelCase = starting_batch_size def decorator(*lowerCAmelCase , **lowerCAmelCase ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() UpperCAmelCase = list(inspect.signature(lowerCAmelCase ).parameters.keys() ) # Guard against user error if len(lowerCAmelCase ) < (len(lowerCAmelCase ) + 1): UpperCAmelCase = """, """.join([F'''{arg}={value}''' for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F'''Batch size was passed into `{function.__name__}` as the first argument when called.''' F'''Remove this as the decorator already does so: `{function.__name__}({arg_str})`''' ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(lowerCAmelCase , *lowerCAmelCase , **lowerCAmelCase ) except Exception as e: if should_reduce_batch_size(lowerCAmelCase ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
673
0
from __future__ import annotations import os from typing import Any import requests lowerCamelCase = '''https://api.github.com''' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user lowerCamelCase = BASE_URL + '''/user''' # https://github.com/settings/tokens lowerCamelCase = os.environ.get('USER_TOKEN', '') def a_ ( SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' _lowerCamelCase : List[Any] ={ 'Authorization': F'''token {auth_token}''', 'Accept': 'application/vnd.github.v3+json', } return requests.get(SCREAMING_SNAKE_CASE__ , headers=SCREAMING_SNAKE_CASE__ ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(F"""{key}: {value}""") else: raise ValueError('\'USER_TOKEN\' field cannot be empty.')
464
"""simple docstring""" import math def _lowerCAmelCase ( lowerCAmelCase = 100 ): '''simple docstring''' UpperCAmelCase = sum(i * i for i in range(1 , n + 1 ) ) UpperCAmelCase = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F'{solution() = }')
673
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase : str = { '''configuration_poolformer''': [ '''POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PoolFormerConfig''', '''PoolFormerOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = ['''PoolFormerFeatureExtractor'''] UpperCAmelCase : Dict = ['''PoolFormerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[int] = [ '''POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PoolFormerForImageClassification''', '''PoolFormerModel''', '''PoolFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys UpperCAmelCase : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure)
567
"""simple docstring""" def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [0] * len(lowerCAmelCase ) UpperCAmelCase = [] UpperCAmelCase = [1] * len(lowerCAmelCase ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCAmelCase ) ): if indegree[i] == 0: queue.append(lowerCAmelCase ) while queue: UpperCAmelCase = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: UpperCAmelCase = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(lowerCAmelCase ) print(max(lowerCAmelCase ) ) # Adjacency list of Graph lowerCAmelCase_ : str = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
673
0
'''simple docstring''' import math def lowerCAmelCase_ ( _lowerCamelCase: Dict ): return math.sqrt(_lowerCamelCase ) * math.sqrt(_lowerCamelCase ) == num def lowerCAmelCase_ ( _lowerCamelCase: Optional[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 __SCREAMING_SNAKE_CASE : Optional[Any] = n while left <= right: __SCREAMING_SNAKE_CASE : str = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: __SCREAMING_SNAKE_CASE : Tuple = mid - 1 else: __SCREAMING_SNAKE_CASE : Optional[int] = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
578
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase_ ( a_ ): _A : Optional[int] = 'facebook/bart-large-mnli' _A : Union[str, Any] = ( 'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ' 'should be the text to classify, and `labels`, which should be the list of labels to use for classification. ' 'It returns the most likely label in the list of provided `labels` for the input text.' ) _A : Dict = 'text_classifier' _A : Union[str, Any] = AutoTokenizer _A : Tuple = AutoModelForSequenceClassification _A : Optional[int] = ['text', ['text']] _A : Dict = ['text'] def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" super().setup() UpperCAmelCase = self.model.config UpperCAmelCase = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): UpperCAmelCase = int(snake_case__ ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = labels return self.pre_processor( [text] * len(snake_case__ ) , [f'''This example is {label}''' for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def UpperCamelCase_ ( self , snake_case__ ) -> str: """simple docstring""" UpperCAmelCase = outputs.logits UpperCAmelCase = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
673
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : Optional[Any] = logging.get_logger(__name__) lowercase__ : Dict = { '''naver-clova-ix/donut-base''': '''https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json''', # See all Donut models at https://huggingface.co/models?filter=donut-swin } class _UpperCAmelCase ( a_): _lowerCAmelCase : Union[str, Any] = 'donut-swin' _lowerCAmelCase : str = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : int , lowercase_ : List[Any]=224 , lowercase_ : Union[str, Any]=4 , lowercase_ : Union[str, Any]=3 , lowercase_ : Optional[Any]=96 , lowercase_ : Any=[2, 2, 6, 2] , lowercase_ : Any=[3, 6, 12, 24] , lowercase_ : List[Any]=7 , lowercase_ : Optional[Any]=4.0 , lowercase_ : str=True , lowercase_ : Tuple=0.0 , lowercase_ : Tuple=0.0 , lowercase_ : List[Any]=0.1 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : Tuple=False , lowercase_ : Any=0.02 , lowercase_ : int=1E-5 , **lowercase_ : Union[str, Any] , ): super().__init__(**snake_case__ ) snake_case_ : List[Any] = image_size snake_case_ : int = patch_size snake_case_ : Optional[Any] = num_channels snake_case_ : Dict = embed_dim snake_case_ : List[Any] = depths snake_case_ : List[str] = len(snake_case__ ) snake_case_ : int = num_heads snake_case_ : str = window_size snake_case_ : Tuple = mlp_ratio snake_case_ : Tuple = qkv_bias snake_case_ : Optional[Any] = hidden_dropout_prob snake_case_ : Optional[int] = attention_probs_dropout_prob snake_case_ : Optional[Any] = drop_path_rate snake_case_ : int = hidden_act snake_case_ : str = use_absolute_embeddings snake_case_ : Any = layer_norm_eps snake_case_ : Tuple = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case_ : int = int(embed_dim * 2 ** (len(snake_case__ ) - 1) )
123
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class UpperCamelCase_ ( a_ ): _A : Union[List[PIL.Image.Image], np.ndarray] _A : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
673
0
'''simple docstring''' import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class __lowerCamelCase ( a_ , a_ ): '''simple docstring''' snake_case__ : int = 1 @register_to_config def __init__( self , a__=2000 , a__=0.1 , a__=20 , a__=1e-3 ): __SCREAMING_SNAKE_CASE : List[Any] = None __SCREAMING_SNAKE_CASE : Any = None __SCREAMING_SNAKE_CASE : Optional[Any] = None def a_ ( self , a__ , a__ = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = torch.linspace(1 , self.config.sampling_eps , snake_case__ , device=snake_case__ ) def a_ ( self , a__ , a__ , a__ , a__=None ): if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __SCREAMING_SNAKE_CASE : List[str] = ( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __SCREAMING_SNAKE_CASE : List[str] = std.flatten() while len(std.shape ) < len(score.shape ): __SCREAMING_SNAKE_CASE : str = std.unsqueeze(-1 ) __SCREAMING_SNAKE_CASE : Optional[Any] = -score / std # compute __SCREAMING_SNAKE_CASE : Union[str, Any] = -1.0 / len(self.timesteps ) __SCREAMING_SNAKE_CASE : List[str] = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __SCREAMING_SNAKE_CASE : List[Any] = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __SCREAMING_SNAKE_CASE : int = beta_t.unsqueeze(-1 ) __SCREAMING_SNAKE_CASE : List[Any] = -0.5 * beta_t * x __SCREAMING_SNAKE_CASE : Any = torch.sqrt(snake_case__ ) __SCREAMING_SNAKE_CASE : List[Any] = drift - diffusion**2 * score __SCREAMING_SNAKE_CASE : Tuple = x + drift * dt # add noise __SCREAMING_SNAKE_CASE : Any = randn_tensor(x.shape , layout=x.layout , generator=snake_case__ , device=x.device , dtype=x.dtype ) __SCREAMING_SNAKE_CASE : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self ): return self.config.num_train_timesteps
211
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCAmelCase_ : Any = { '''configuration_encodec''': [ '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EncodecConfig''', ], '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EncodecModel''', '''EncodecPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
673
0
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __a: Union[str, Any] = logging.get_logger(__name__) __a: int = { '''linear''': get_linear_schedule_with_warmup, '''cosine''': get_cosine_schedule_with_warmup, '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup, '''polynomial''': get_polynomial_decay_schedule_with_warmup, '''constant''': get_constant_schedule, '''constant_w_warmup''': get_constant_schedule_with_warmup, } class UpperCAmelCase ( a_ ): '''simple docstring''' def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , *__lowerCAmelCase , **__lowerCAmelCase ) -> Tuple: super().__init__(*snake_case__ , **snake_case__ ) if config is None: assert isinstance(self.model , snake_case__ ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) lowercase__ : List[Any] = self.model.config else: lowercase__ : Optional[int] = config lowercase__ : Dict = data_args lowercase__ : List[str] = self.config.tgt_vocab_size if isinstance(self.config , snake_case__ ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ''' padding..''' ) if self.args.label_smoothing == 0: lowercase__ : Any = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss lowercase__ : Tuple = label_smoothed_nll_loss def _lowerCAmelCase( self , __lowerCAmelCase ) -> Union[str, Any]: if self.optimizer is None: lowercase__ : int = ['''bias''', '''LayerNorm.weight'''] lowercase__ : Optional[Any] = [ { '''params''': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], '''weight_decay''': self.args.weight_decay, }, { '''params''': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], '''weight_decay''': 0.0, }, ] lowercase__ : Any = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: lowercase__ : List[str] = Adafactor lowercase__ : int = {'''scale_parameter''': False, '''relative_step''': False} else: lowercase__ : int = AdamW lowercase__ : List[Any] = { '''betas''': (self.args.adam_betaa, self.args.adam_betaa), '''eps''': self.args.adam_epsilon, } lowercase__ : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: lowercase__ : List[Any] = OSS( params=snake_case__ , optim=snake_case__ , **snake_case__ , ) else: lowercase__ : Tuple = optimizer_cls(snake_case__ , **snake_case__ ) if self.lr_scheduler is None: lowercase__ : Optional[Any] = self._get_lr_scheduler(snake_case__ ) else: # ignoring --lr_scheduler logger.warning('''scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.''' ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> str: lowercase__ : Optional[Any] = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": lowercase__ : Optional[Any] = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": lowercase__ : str = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: lowercase__ : Optional[int] = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=snake_case__ ) return scheduler def _lowerCAmelCase( self ) -> Optional[torch.utils.data.Sampler]: if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token lowercase__ : Optional[Any] = model(**snake_case__ , use_cache=snake_case__ )[0] lowercase__ : str = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models lowercase__ , lowercase__ : List[Any] = model(**snake_case__ , labels=snake_case__ , use_cache=snake_case__ )[:2] else: # compute label smoothed loss lowercase__ : Tuple = model(**snake_case__ , use_cache=snake_case__ )[0] lowercase__ : Union[str, Any] = torch.nn.functional.log_softmax(snake_case__ , dim=-1 ) lowercase__ , lowercase__ : Tuple = self.loss_fn(snake_case__ , snake_case__ , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: lowercase__ : List[str] = inputs.pop('''labels''' ) lowercase__ , lowercase__ : int = self._compute_loss(snake_case__ , snake_case__ , snake_case__ ) return loss def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = None , ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: lowercase__ : int = self._prepare_inputs(snake_case__ ) lowercase__ : Union[str, Any] = { '''max_length''': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, '''num_beams''': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: lowercase__ : Tuple = self.model.generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , **snake_case__ , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: lowercase__ : List[Any] = self._pad_tensors_to_max_len(snake_case__ , gen_kwargs['''max_length'''] ) lowercase__ : Any = inputs.pop('''labels''' ) with torch.no_grad(): # compute loss on predict data lowercase__ , lowercase__ : List[str] = self._compute_loss(snake_case__ , snake_case__ , snake_case__ ) lowercase__ : Any = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) lowercase__ : str = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: lowercase__ : Tuple = self._pad_tensors_to_max_len(snake_case__ , gen_kwargs['''max_length'''] ) return (loss, logits, labels) def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: lowercase__ : List[str] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( '''Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be''' F""" padded to `max_length`={max_length}""" ) lowercase__ : Tuple = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) lowercase__ : Optional[Any] = tensor return padded_tensor
152
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
673
0
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": __lowercase : List[str] = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) __lowercase : Optional[Any] = parser.parse_args() __lowercase : Optional[Any] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) __lowercase : List[str] = CLIPImageProcessor() __lowercase : str = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') __lowercase : Optional[Any] = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
476
"""simple docstring""" import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : str = VideoToVideoSDPipeline _A : List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'} ) - {'image', 'width', 'height'} _A : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'} ) - {'image'} _A : int = PipelineTesterMixin.required_optional_params - {'latents'} _A : List[str] = False # No `output_type`. _A : Any = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'return_dict', 'callback', 'callback_steps', ] ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) UpperCAmelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=snake_case__ , set_alpha_to_one=snake_case__ , ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="""gelu""" , projection_dim=5_12 , ) UpperCAmelCase = CLIPTextModel(snake_case__ ) UpperCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCAmelCase = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def UpperCamelCase_ ( self , snake_case__ , snake_case__=0 ) -> List[str]: """simple docstring""" UpperCAmelCase = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) if str(snake_case__ ).startswith("""mps""" ): UpperCAmelCase = torch.manual_seed(snake_case__ ) else: UpperCAmelCase = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) UpperCAmelCase = { """prompt""": """A painting of a squirrel eating a burger""", """video""": video, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = VideoToVideoSDPipeline(**snake_case__ ) UpperCAmelCase = sd_pipe.to(snake_case__ ) sd_pipe.set_progress_bar_config(disable=snake_case__ ) UpperCAmelCase = self.get_dummy_inputs(snake_case__ ) UpperCAmelCase = """np""" UpperCAmelCase = sd_pipe(**snake_case__ ).frames UpperCAmelCase = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) UpperCAmelCase = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=snake_case__ , expected_max_diff=5e-3 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return super().test_progress_bar() @slow @skip_mps class UpperCamelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = VideoToVideoSDPipeline.from_pretrained("""cerspense/zeroscope_v2_XL""" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames UpperCAmelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCAmelCase = torch.randn((1, 10, 3, 10_24, 5_76) , generator=snake_case__ ) UpperCAmelCase = video.to("""cuda""" ) UpperCAmelCase = """Spiderman is surfing""" UpperCAmelCase = pipe(snake_case__ , video=snake_case__ , generator=snake_case__ , num_inference_steps=3 , output_type="""pt""" ).frames UpperCAmelCase = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
673
0
from __future__ import annotations from typing import Any def UpperCAmelCase ( UpperCAmelCase )-> Union[str, Any]: '''simple docstring''' create_state_space_tree(UpperCAmelCase ,[] ,0 ) def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase )-> Optional[int]: '''simple docstring''' if index == len(UpperCAmelCase ): print(UpperCAmelCase ) return create_state_space_tree(UpperCAmelCase ,UpperCAmelCase ,index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(UpperCAmelCase ,UpperCAmelCase ,index + 1 ) current_subsequence.pop() if __name__ == "__main__": A_ = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
393
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : int = logging.get_logger(__name__) lowerCAmelCase_ : Any = { '''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''', # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class UpperCamelCase_ ( a_ ): _A : int = 'wav2vec2' def __init__( self , snake_case__=32 , snake_case__=7_68 , snake_case__=12 , snake_case__=12 , snake_case__=30_72 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.02 , snake_case__=1e-5 , snake_case__="group" , snake_case__="gelu" , snake_case__=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , snake_case__=(5, 2, 2, 2, 2, 2, 2) , snake_case__=(10, 3, 3, 3, 3, 2, 2) , snake_case__=False , snake_case__=1_28 , snake_case__=16 , snake_case__=False , snake_case__=True , snake_case__=0.05 , snake_case__=10 , snake_case__=2 , snake_case__=0.0 , snake_case__=10 , snake_case__=0 , snake_case__=3_20 , snake_case__=2 , snake_case__=0.1 , snake_case__=1_00 , snake_case__=2_56 , snake_case__=2_56 , snake_case__=0.1 , snake_case__="sum" , snake_case__=False , snake_case__=False , snake_case__=2_56 , snake_case__=(5_12, 5_12, 5_12, 5_12, 15_00) , snake_case__=(5, 3, 3, 1, 1) , snake_case__=(1, 2, 3, 1, 1) , snake_case__=5_12 , snake_case__=0 , snake_case__=1 , snake_case__=2 , snake_case__=False , snake_case__=3 , snake_case__=2 , snake_case__=3 , snake_case__=None , snake_case__=None , **snake_case__ , ) -> Optional[Any]: """simple docstring""" super().__init__(**snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ ) UpperCAmelCase = hidden_size UpperCAmelCase = feat_extract_norm UpperCAmelCase = feat_extract_activation UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = conv_bias UpperCAmelCase = num_conv_pos_embeddings UpperCAmelCase = num_conv_pos_embedding_groups UpperCAmelCase = len(self.conv_dim ) UpperCAmelCase = num_hidden_layers UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = feat_proj_dropout UpperCAmelCase = final_dropout UpperCAmelCase = layerdrop UpperCAmelCase = layer_norm_eps UpperCAmelCase = initializer_range UpperCAmelCase = vocab_size UpperCAmelCase = do_stable_layer_norm UpperCAmelCase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks # parameters for pretraining with codevector quantized representations UpperCAmelCase = num_codevectors_per_group UpperCAmelCase = num_codevector_groups UpperCAmelCase = contrastive_logits_temperature UpperCAmelCase = feat_quantizer_dropout UpperCAmelCase = num_negatives UpperCAmelCase = codevector_dim UpperCAmelCase = proj_codevector_dim UpperCAmelCase = diversity_loss_weight # ctc loss UpperCAmelCase = ctc_loss_reduction UpperCAmelCase = ctc_zero_infinity # adapter UpperCAmelCase = add_adapter UpperCAmelCase = adapter_kernel_size UpperCAmelCase = adapter_stride UpperCAmelCase = num_adapter_layers UpperCAmelCase = output_hidden_size or hidden_size UpperCAmelCase = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = xvector_output_dim @property def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
673
0
def lowercase__ ( __snake_case : Optional[int] ): '''simple docstring''' if n == 1 or not isinstance(__snake_case , __snake_case ): return 0 elif n == 2: return 1 else: UpperCAmelCase_ : Tuple = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def lowercase__ ( __snake_case : Dict ): '''simple docstring''' UpperCAmelCase_ : int = 0 UpperCAmelCase_ : Dict = 2 while digits < n: index += 1 UpperCAmelCase_ : Tuple = len(str(fibonacci(__snake_case ) ) ) return index def lowercase__ ( __snake_case : Union[str, Any] = 1_000 ): '''simple docstring''' return fibonacci_digits_index(__snake_case ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
406
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowerCAmelCase_ : Optional[Any] = NewType('''DataClass''', Any) lowerCAmelCase_ : Any = NewType('''DataClassType''', Any) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' if isinstance(lowerCAmelCase , lowerCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = {str(lowerCAmelCase ): choice for choice in choices} return lambda lowerCAmelCase : str_to_choice.get(lowerCAmelCase , lowerCAmelCase ) def _lowerCAmelCase ( *, lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = dataclasses.MISSING , lowerCAmelCase = dataclasses.MISSING , lowerCAmelCase = None , **lowerCAmelCase , ): '''simple docstring''' if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls UpperCAmelCase = {} if aliases is not None: UpperCAmelCase = aliases if help is not None: UpperCAmelCase = help return dataclasses.field(metadata=lowerCAmelCase , default=lowerCAmelCase , default_factory=lowerCAmelCase , **lowerCAmelCase ) class UpperCamelCase_ ( a_ ): _A : Iterable[DataClassType] def __init__( self , snake_case__ , **snake_case__ ) -> List[str]: """simple docstring""" if "formatter_class" not in kwargs: UpperCAmelCase = ArgumentDefaultsHelpFormatter super().__init__(**snake_case__ ) if dataclasses.is_dataclass(snake_case__ ): UpperCAmelCase = [dataclass_types] UpperCAmelCase = list(snake_case__ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(snake_case__ ) @staticmethod def UpperCamelCase_ ( snake_case__ , snake_case__ ) -> str: """simple docstring""" UpperCAmelCase = f'''--{field.name}''' UpperCAmelCase = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , snake_case__ ): raise RuntimeError( """Unresolved type detected, which should have been done with the help of """ """`typing.get_type_hints` method by default""" ) UpperCAmelCase = kwargs.pop("""aliases""" , [] ) if isinstance(snake_case__ , snake_case__ ): UpperCAmelCase = [aliases] UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) if origin_type is Union or (hasattr(snake_case__ , """UnionType""" ) and isinstance(snake_case__ , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(snake_case__ ) not in field.type.__args__ ): raise ValueError( """Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because""" """ the argument parser only supports one type per argument.""" f''' Problem encountered in field \'{field.name}\'.''' ) if type(snake_case__ ) not in field.type.__args__: # filter `str` in Union UpperCAmelCase = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) UpperCAmelCase = ( field.type.__args__[0] if isinstance(snake_case__ , field.type.__args__[1] ) else field.type.__args__[1] ) UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) UpperCAmelCase = {} if origin_type is Literal or (isinstance(field.type , snake_case__ ) and issubclass(field.type , snake_case__ )): if origin_type is Literal: UpperCAmelCase = field.type.__args__ else: UpperCAmelCase = [x.value for x in field.type] UpperCAmelCase = make_choice_type_function(kwargs["""choices"""] ) if field.default is not dataclasses.MISSING: UpperCAmelCase = field.default else: UpperCAmelCase = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument UpperCAmelCase = copy(snake_case__ ) # Hack because type=bool in argparse does not behave as we want. UpperCAmelCase = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. UpperCAmelCase = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way UpperCAmelCase = default # This tells argparse we accept 0 or 1 value after --field_name UpperCAmelCase = """?""" # This is the value that will get picked if we do --field_name (without value) UpperCAmelCase = True elif isclass(snake_case__ ) and issubclass(snake_case__ , snake_case__ ): UpperCAmelCase = field.type.__args__[0] UpperCAmelCase = """+""" if field.default_factory is not dataclasses.MISSING: UpperCAmelCase = field.default_factory() elif field.default is dataclasses.MISSING: UpperCAmelCase = True else: UpperCAmelCase = field.type if field.default is not dataclasses.MISSING: UpperCAmelCase = field.default elif field.default_factory is not dataclasses.MISSING: UpperCAmelCase = field.default_factory() else: UpperCAmelCase = True parser.add_argument(snake_case__ , *snake_case__ , **snake_case__ ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): UpperCAmelCase = False parser.add_argument(f'''--no_{field.name}''' , action="""store_false""" , dest=field.name , **snake_case__ ) def UpperCamelCase_ ( self , snake_case__ ) -> Any: """simple docstring""" if hasattr(snake_case__ , """_argument_group_name""" ): UpperCAmelCase = self.add_argument_group(dtype._argument_group_name ) else: UpperCAmelCase = self try: UpperCAmelCase = get_type_hints(snake_case__ ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' """removing line of `from __future__ import annotations` which opts in Postponed """ """Evaluation of Annotations (PEP 563)""" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(snake_case__ ): UpperCAmelCase = """.""".join(map(snake_case__ , sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' """line of `from __future__ import annotations` which opts in union types as """ """`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To """ """support Python versions that lower than 3.10, you need to use """ """`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of """ """`X | None`.""" ) from ex raise for field in dataclasses.fields(snake_case__ ): if not field.init: continue UpperCAmelCase = type_hints[field.name] self._parse_dataclass_field(snake_case__ , snake_case__ ) def UpperCamelCase_ ( self , snake_case__=None , snake_case__=False , snake_case__=True , snake_case__=None , snake_case__=None , ) -> Tuple[DataClass, ...]: """simple docstring""" if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): UpperCAmelCase = [] if args_filename: args_files.append(Path(snake_case__ ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(""".args""" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values UpperCAmelCase = ArgumentParser() args_file_parser.add_argument(snake_case__ , type=snake_case__ , action="""append""" ) # Use only remaining args for further parsing (remove the args_file_flag) UpperCAmelCase , UpperCAmelCase = args_file_parser.parse_known_args(args=snake_case__ ) UpperCAmelCase = vars(snake_case__ ).get(args_file_flag.lstrip("""-""" ) , snake_case__ ) if cmd_args_file_paths: args_files.extend([Path(snake_case__ ) for p in cmd_args_file_paths] ) UpperCAmelCase = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last UpperCAmelCase = file_args + args if args is not None else file_args + sys.argv[1:] UpperCAmelCase , UpperCAmelCase = self.parse_known_args(args=snake_case__ ) UpperCAmelCase = [] for dtype in self.dataclass_types: UpperCAmelCase = {f.name for f in dataclasses.fields(snake_case__ ) if f.init} UpperCAmelCase = {k: v for k, v in vars(snake_case__ ).items() if k in keys} for k in keys: delattr(snake_case__ , snake_case__ ) UpperCAmelCase = dtype(**snake_case__ ) outputs.append(snake_case__ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(snake_case__ ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" UpperCAmelCase = set(args.keys() ) UpperCAmelCase = [] for dtype in self.dataclass_types: UpperCAmelCase = {f.name for f in dataclasses.fields(snake_case__ ) if f.init} UpperCAmelCase = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) UpperCAmelCase = dtype(**snake_case__ ) outputs.append(snake_case__ ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(snake_case__ )}''' ) return tuple(snake_case__ ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" with open(Path(snake_case__ ) , encoding="""utf-8""" ) as open_json_file: UpperCAmelCase = json.loads(open_json_file.read() ) UpperCAmelCase = self.parse_dict(snake_case__ , allow_extra_keys=snake_case__ ) return tuple(snake_case__ ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" UpperCAmelCase = self.parse_dict(yaml.safe_load(Path(snake_case__ ).read_text() ) , allow_extra_keys=snake_case__ ) return tuple(snake_case__ )
673
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device __UpperCAmelCase =False class lowerCAmelCase__ ( unittest.TestCase ): pass @nightly @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def lowercase_ ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self ): '''simple docstring''' A__ = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(snake_case__ ) pipe.set_progress_bar_config(disable=snake_case__ ) A__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) A__ = torch.manual_seed(0 ) A__ = pipe.dual_guided( prompt="first prompt" , image=snake_case__ , text_to_image_strength=0.75 , generator=snake_case__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(snake_case__ ) A__ = VersatileDiffusionPipeline.from_pretrained(snake_case__ , torch_dtype=torch.floataa ) pipe.to(snake_case__ ) pipe.set_progress_bar_config(disable=snake_case__ ) A__ = generator.manual_seed(0 ) A__ = pipe.dual_guided( prompt="first prompt" , image=snake_case__ , text_to_image_strength=0.75 , generator=snake_case__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def lowercase_ ( self ): '''simple docstring''' A__ = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(snake_case__ ) pipe.set_progress_bar_config(disable=snake_case__ ) A__ = "cyberpunk 2077" A__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) A__ = torch.manual_seed(0 ) A__ = pipe.dual_guided( prompt=snake_case__ , image=snake_case__ , text_to_image_strength=0.75 , generator=snake_case__ , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" , ).images A__ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) A__ = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 A__ = "A painting of a squirrel eating a burger " A__ = torch.manual_seed(0 ) A__ = pipe.text_to_image( prompt=snake_case__ , generator=snake_case__ , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" ).images A__ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) A__ = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 A__ = pipe.image_variation(snake_case__ , generator=snake_case__ , output_type="numpy" ).images A__ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) A__ = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
337
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCAmelCase_ : List[str] = False class UpperCamelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self , snake_case__=32 ) -> Optional[Any]: """simple docstring""" set_seed(0 ) UpperCAmelCase = UNetaDModel(sample_size=snake_case__ , in_channels=3 , out_channels=3 ) UpperCAmelCase = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable UpperCAmelCase = DDPMScheduler( num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) UpperCAmelCase = DDIMScheduler( num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) UpperCAmelCase = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(snake_case__ ) for _ in range(4 )] UpperCAmelCase = [torch.randn((4, 3, 32, 32) ).to(snake_case__ ) for _ in range(4 )] UpperCAmelCase = [torch.randint(0 , 10_00 , (4,) ).long().to(snake_case__ ) for _ in range(4 )] # train with a DDPM scheduler UpperCAmelCase , UpperCAmelCase = self.get_model_optimizer(resolution=32 ) model.train().to(snake_case__ ) for i in range(4 ): optimizer.zero_grad() UpperCAmelCase = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) UpperCAmelCase = model(snake_case__ , timesteps[i] ).sample UpperCAmelCase = torch.nn.functional.mse_loss(snake_case__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM UpperCAmelCase , UpperCAmelCase = self.get_model_optimizer(resolution=32 ) model.train().to(snake_case__ ) for i in range(4 ): optimizer.zero_grad() UpperCAmelCase = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) UpperCAmelCase = model(snake_case__ , timesteps[i] ).sample UpperCAmelCase = torch.nn.functional.mse_loss(snake_case__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-5 ) )
673
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={ '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class a__ ( a_ ): lowerCamelCase : str ='vit_msn' def __init__( self : List[str] , a : Dict=7_68 , a : List[Any]=12 , a : Dict=12 , a : Dict=30_72 , a : Dict="gelu" , a : Optional[int]=0.0 , a : Union[str, Any]=0.0 , a : Any=0.02 , a : Dict=1e-0_6 , a : Optional[Any]=2_24 , a : Optional[Any]=16 , a : Dict=3 , a : Dict=True , **a : List[Any] , ): """simple docstring""" super().__init__(**snake_case__ ) __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = image_size __lowerCamelCase = patch_size __lowerCamelCase = num_channels __lowerCamelCase = qkv_bias
546
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class UpperCamelCase_ : def __init__( self , snake_case__=2 , snake_case__=3 , snake_case__=64 , snake_case__=None ) -> List[str]: """simple docstring""" UpperCAmelCase = np.random.default_rng(snake_case__ ) UpperCAmelCase = length UpperCAmelCase = rng.normal(size=(length,) ).astype(np.floataa ) UpperCAmelCase = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> int: """simple docstring""" return self.length def __getitem__( self , snake_case__ ) -> Tuple: """simple docstring""" return {"x": self.x[i], "y": self.y[i]} class UpperCamelCase_ ( torch.nn.Module ): def __init__( self , snake_case__=0 , snake_case__=0 , snake_case__=False ) -> List[str]: """simple docstring""" super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = True def UpperCamelCase_ ( self , snake_case__=None ) -> List[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCAmelCase = False return x * self.a[0] + self.b[0] class UpperCamelCase_ ( torch.nn.Module ): def __init__( self , snake_case__=0 , snake_case__=0 , snake_case__=False ) -> List[Any]: """simple docstring""" super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor(snake_case__ ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor(snake_case__ ).float() ) UpperCAmelCase = True def UpperCamelCase_ ( self , snake_case__=None ) -> Optional[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCAmelCase = False return x * self.a + self.b def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase = 16 ): '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer UpperCAmelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCAmelCase = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} UpperCAmelCase = load_dataset("""csv""" , data_files=lowerCAmelCase ) UpperCAmelCase = datasets["""train"""].unique("""label""" ) UpperCAmelCase = {v: i for i, v in enumerate(lowerCAmelCase )} def tokenize_function(lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase , max_length=lowerCAmelCase , padding="""max_length""" ) if "label" in examples: UpperCAmelCase = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase = datasets.map( lowerCAmelCase , batched=lowerCAmelCase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowerCAmelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCAmelCase = DataLoader(tokenized_datasets["""train"""] , shuffle=lowerCAmelCase , collate_fn=lowerCAmelCase , batch_size=2 ) UpperCAmelCase = DataLoader(tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase , collate_fn=lowerCAmelCase , batch_size=1 ) return train_dataloader, eval_dataloader
673
0
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt') @dataclass class A : UpperCamelCase__ : Optional[str] =field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) UpperCamelCase__ : Optional[str] =field( default=a_ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) UpperCamelCase__ : Optional[str] =field( default=a_ , metadata={'help': 'The column name of the images in the files.'} ) UpperCamelCase__ : Optional[str] =field(default=a_ , metadata={'help': 'A folder containing the training data.'} ) UpperCamelCase__ : Optional[str] =field(default=a_ , metadata={'help': 'A folder containing the validation data.'} ) UpperCamelCase__ : Optional[float] =field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) UpperCamelCase__ : Optional[int] =field( default=a_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) UpperCamelCase__ : Optional[int] =field( default=a_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def lowerCamelCase ( self : List[str] ) -> List[Any]: """simple docstring""" _lowerCamelCase : List[str] ={} if self.train_dir is not None: _lowerCamelCase : List[str] =self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple =self.validation_dir _lowerCamelCase : List[str] =data_files if data_files else None @dataclass class A : UpperCamelCase__ : str =field( default=a_ , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) UpperCamelCase__ : Optional[str] =field( default=a_ , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) UpperCamelCase__ : Optional[str] =field( default=a_ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) UpperCamelCase__ : Optional[str] =field( default=a_ , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) UpperCamelCase__ : str =field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) UpperCamelCase__ : str =field(default=a_ , metadata={'help': 'Name or path of preprocessor config.'} ) UpperCamelCase__ : bool =field( default=a_ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) UpperCamelCase__ : float =field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) UpperCamelCase__ : bool =field( default=a_ , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class A ( a_ ): UpperCamelCase__ : float =field( default=1E-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def a_ ( SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' _lowerCamelCase : Tuple =torch.stack([example['pixel_values'] for example in examples] ) return {"pixel_values": pixel_values} def a_ ( ): '''simple docstring''' _lowerCamelCase : Any =HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Any =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mae' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Optional[int] =training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE__ ) transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Union[str, Any] =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset. _lowerCamelCase : int =load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : str =None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , SCREAMING_SNAKE_CASE__ ) and data_args.train_val_split > 0.0: _lowerCamelCase : Union[str, Any] =ds['train'].train_test_split(data_args.train_val_split ) _lowerCamelCase : Dict =split['train'] _lowerCamelCase : List[str] =split['test'] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : Optional[int] ={ 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Tuple =ViTMAEConfig.from_pretrained(model_args.config_name , **SCREAMING_SNAKE_CASE__ ) elif model_args.model_name_or_path: _lowerCamelCase : List[Any] =ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE__ ) else: _lowerCamelCase : Union[str, Any] =ViTMAEConfig() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(F'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(F'''New config: {config}''' ) # adapt config config.update( { 'mask_ratio': model_args.mask_ratio, 'norm_pix_loss': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : List[Any] =ViTImageProcessor.from_pretrained(model_args.image_processor_name , **SCREAMING_SNAKE_CASE__ ) elif model_args.model_name_or_path: _lowerCamelCase : Optional[int] =ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE__ ) else: _lowerCamelCase : int =ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[str] =ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) _lowerCamelCase : Any =ViTMAEForPreTraining(SCREAMING_SNAKE_CASE__ ) if training_args.do_train: _lowerCamelCase : List[str] =ds['train'].column_names else: _lowerCamelCase : Optional[Any] =ds['validation'].column_names if data_args.image_column_name is not None: _lowerCamelCase : int =data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Union[str, Any] ='image' elif "img" in column_names: _lowerCamelCase : int ='img' else: _lowerCamelCase : List[str] =column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Optional[int] =image_processor.size['shortest_edge'] else: _lowerCamelCase : List[str] =(image_processor.size['height'], image_processor.size['width']) _lowerCamelCase : Optional[int] =Compose( [ Lambda(lambda SCREAMING_SNAKE_CASE__ : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(SCREAMING_SNAKE_CASE__ , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(SCREAMING_SNAKE_CASE__ : int ): _lowerCamelCase : str =[transforms(SCREAMING_SNAKE_CASE__ ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: _lowerCamelCase : Dict =ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(SCREAMING_SNAKE_CASE__ ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: _lowerCamelCase : List[Any] =( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(SCREAMING_SNAKE_CASE__ ) # Compute absolute learning rate _lowerCamelCase : Any =( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : List[str] =training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : List[Any] =Trainer( model=SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=SCREAMING_SNAKE_CASE__ , data_collator=SCREAMING_SNAKE_CASE__ , ) # Training if training_args.do_train: _lowerCamelCase : Tuple =None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : Optional[Any] =training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Any =last_checkpoint _lowerCamelCase : List[str] =trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE__ ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : Dict =trainer.evaluate() trainer.log_metrics('eval' , SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('eval' , SCREAMING_SNAKE_CASE__ ) # Write model card and (optionally) push to hub _lowerCamelCase : List[Any] ={ 'tasks': 'masked-auto-encoding', 'dataset': data_args.dataset_name, 'tags': ['masked-auto-encoding'], } if training_args.push_to_hub: trainer.push_to_hub(**SCREAMING_SNAKE_CASE__ ) else: trainer.create_model_card(**SCREAMING_SNAKE_CASE__ ) def a_ ( SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' main() if __name__ == "__main__": main()
464
"""simple docstring""" import flax.linen as nn import jax import jax.numpy as jnp class UpperCamelCase_ ( nn.Module ): _A : int _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , snake_case__ ) -> Tuple: """simple docstring""" UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = hidden_states.shape UpperCAmelCase = jax.image.resize( snake_case__ , shape=(batch, height * 2, width * 2, channels) , method="""nearest""" , ) UpperCAmelCase = self.conv(snake_case__ ) return hidden_states class UpperCamelCase_ ( nn.Module ): _A : int _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , snake_case__ ) -> Any: """simple docstring""" UpperCAmelCase = self.conv(snake_case__ ) return hidden_states class UpperCamelCase_ ( nn.Module ): _A : int _A : int = None _A : float = 0.0 _A : bool = None _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.in_channels if self.out_channels is None else self.out_channels UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = nn.Dense(snake_case__ , dtype=self.dtype ) UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Dropout(self.dropout_prob ) UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut UpperCAmelCase = None if use_nin_shortcut: UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(1, 1) , strides=(1, 1) , padding="""VALID""" , dtype=self.dtype , ) def __call__( self , snake_case__ , snake_case__ , snake_case__=True ) -> List[Any]: """simple docstring""" UpperCAmelCase = hidden_states UpperCAmelCase = self.norma(snake_case__ ) UpperCAmelCase = nn.swish(snake_case__ ) UpperCAmelCase = self.conva(snake_case__ ) UpperCAmelCase = self.time_emb_proj(nn.swish(snake_case__ ) ) UpperCAmelCase = jnp.expand_dims(jnp.expand_dims(snake_case__ , 1 ) , 1 ) UpperCAmelCase = hidden_states + temb UpperCAmelCase = self.norma(snake_case__ ) UpperCAmelCase = nn.swish(snake_case__ ) UpperCAmelCase = self.dropout(snake_case__ , snake_case__ ) UpperCAmelCase = self.conva(snake_case__ ) if self.conv_shortcut is not None: UpperCAmelCase = self.conv_shortcut(snake_case__ ) return hidden_states + residual
673
0
"""simple docstring""" from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[Any]=1_3 , lowerCAmelCase_ : int=3_0 , lowerCAmelCase_ : List[Any]=2 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Dict=3_2 , lowerCAmelCase_ : Optional[int]=2 , lowerCAmelCase_ : Any=4 , lowerCAmelCase_ : Tuple=3_7 , lowerCAmelCase_ : Optional[Any]="gelu" , lowerCAmelCase_ : List[str]=0.1 , lowerCAmelCase_ : Tuple=0.1 , lowerCAmelCase_ : Optional[Any]=1_0 , lowerCAmelCase_ : str=0.02 , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : Tuple=0.6 , lowerCAmelCase_ : List[str]=None , ): """simple docstring""" lowercase_ = parent lowercase_ = batch_size lowercase_ = image_size lowercase_ = patch_size lowercase_ = num_channels lowercase_ = is_training lowercase_ = use_labels lowercase_ = hidden_size lowercase_ = num_hidden_layers lowercase_ = num_attention_heads lowercase_ = intermediate_size lowercase_ = hidden_act lowercase_ = hidden_dropout_prob lowercase_ = attention_probs_dropout_prob lowercase_ = type_sequence_label_size lowercase_ = initializer_range lowercase_ = mask_ratio lowercase_ = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowercase_ = (image_size // patch_size) ** 2 lowercase_ = int(math.ceil((1 - mask_ratio) * (num_patches + 1))) def _UpperCAmelCase ( self : Union[str, Any]): """simple docstring""" lowercase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) lowercase_ = None if self.use_labels: lowercase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size) lowercase_ = self.get_config() return config, pixel_values, labels def _UpperCAmelCase ( self : str): """simple docstring""" return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_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=snake_case__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def _UpperCAmelCase ( self : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Tuple): """simple docstring""" lowercase_ = TFViTMAEModel(config=snake_case__) lowercase_ = model(snake_case__ , training=snake_case__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def _UpperCAmelCase ( self : Union[str, Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : Union[str, Any]): """simple docstring""" lowercase_ = TFViTMAEForPreTraining(snake_case__) lowercase_ = model(snake_case__ , training=snake_case__) # expected sequence length = num_patches lowercase_ = (self.image_size // self.patch_size) ** 2 lowercase_ = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels)) # test greyscale images lowercase_ = 1 lowercase_ = TFViTMAEForPreTraining(snake_case__) lowercase_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) lowercase_ = model(snake_case__ , training=snake_case__) lowercase_ = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels)) def _UpperCAmelCase ( self : List[Any]): """simple docstring""" lowercase_ = self.prepare_config_and_inputs() ((lowercase_) , (lowercase_) , (lowercase_)) = config_and_inputs lowercase_ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( a_ , a_ , unittest.TestCase ): lowercase__ = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () lowercase__ = {'feature-extraction': TFViTMAEModel} if is_tf_available() else {} lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def _UpperCAmelCase ( self : Tuple): """simple docstring""" lowercase_ = TFViTMAEModelTester(self) lowercase_ = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=3_7) def _UpperCAmelCase ( self : Optional[int]): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""") def _UpperCAmelCase ( self : Optional[int]): """simple docstring""" pass def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ = model_class(snake_case__) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer)) lowercase_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , tf.keras.layers.Layer)) def _UpperCAmelCase ( self : str): """simple docstring""" lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ = model_class(snake_case__) lowercase_ = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase_ = [*signature.parameters.keys()] lowercase_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case__) def _UpperCAmelCase ( self : int): """simple docstring""" lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__) def _UpperCAmelCase ( self : Union[str, Any]): """simple docstring""" lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*snake_case__) def _UpperCAmelCase ( self : List[Any]): """simple docstring""" np.random.seed(2) lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ = int((config.image_size // config.patch_size) ** 2) lowercase_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) for model_class in self.all_model_classes: lowercase_ = model_class(snake_case__) lowercase_ = self._prepare_for_class(snake_case__ , snake_case__) lowercase_ = model(snake_case__ , noise=snake_case__) lowercase_ = copy.deepcopy(self._prepare_for_class(snake_case__ , snake_case__)) lowercase_ = model(**snake_case__ , noise=snake_case__) lowercase_ = outputs_dict[0].numpy() lowercase_ = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords)) , 1E-6) def _UpperCAmelCase ( self : Union[str, Any]): """simple docstring""" np.random.seed(2) lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ = int((config.image_size // config.patch_size) ** 2) lowercase_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) def prepare_numpy_arrays(lowerCAmelCase_ : List[str]): lowercase_ = {} for k, v in inputs_dict.items(): if tf.is_tensor(snake_case__): lowercase_ = v.numpy() else: lowercase_ = np.array(snake_case__) return inputs_np_dict for model_class in self.all_model_classes: lowercase_ = model_class(snake_case__) lowercase_ = self._prepare_for_class(snake_case__ , snake_case__) lowercase_ = prepare_numpy_arrays(snake_case__) lowercase_ = model(snake_case__ , noise=snake_case__) lowercase_ = model(**snake_case__ , noise=snake_case__) self.assert_outputs_same(snake_case__ , snake_case__) def _UpperCAmelCase ( self : Tuple , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : List[Any]): """simple docstring""" np.random.seed(2) lowercase_ = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2) lowercase_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) lowercase_ = tf.constant(snake_case__) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowercase_ = tf_noise super().check_pt_tf_models(snake_case__ , snake_case__ , snake_case__) def _UpperCAmelCase ( self : Optional[int]): """simple docstring""" np.random.seed(2) lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__),) for module_member_name in dir(snake_case__) if module_member_name.endswith("""MainLayer""") # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len("""MainLayer""")] == model_class.__name__[: -len("""Model""")] for module_member in (getattr(snake_case__ , snake_case__),) if isinstance(snake_case__ , snake_case__) and tf.keras.layers.Layer in module_member.__bases__ and getattr(snake_case__ , """_keras_serializable""" , snake_case__) } lowercase_ = int((config.image_size // config.patch_size) ** 2) lowercase_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) lowercase_ = tf.convert_to_tensor(snake_case__) inputs_dict.update({"""noise""": noise}) for main_layer_class in tf_main_layer_classes: lowercase_ = main_layer_class(snake_case__) lowercase_ = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype) for name, tensor in inputs_dict.items() } lowercase_ = tf.keras.Model(snake_case__ , outputs=main_layer(snake_case__)) lowercase_ = model(snake_case__) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ = os.path.join(snake_case__ , """keras_model.h5""") model.save(snake_case__) lowercase_ = tf.keras.models.load_model( snake_case__ , custom_objects={main_layer_class.__name__: main_layer_class}) assert isinstance(snake_case__ , tf.keras.Model) lowercase_ = model(snake_case__) self.assert_outputs_same(snake_case__ , snake_case__) @slow def _UpperCAmelCase ( self : Any): """simple docstring""" np.random.seed(2) lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ = int((config.image_size // config.patch_size) ** 2) lowercase_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) for model_class in self.all_model_classes: lowercase_ = model_class(snake_case__) lowercase_ = self._prepare_for_class(snake_case__ , snake_case__) lowercase_ = model(snake_case__ , noise=snake_case__) if model_class.__name__ == "TFViTMAEModel": lowercase_ = outputs.last_hidden_state.numpy() lowercase_ = 0 else: lowercase_ = outputs.logits.numpy() lowercase_ = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case__ , saved_model=snake_case__) lowercase_ = model_class.from_pretrained(snake_case__) lowercase_ = model(snake_case__ , noise=snake_case__) if model_class.__name__ == "TFViTMAEModel": lowercase_ = after_outputs["""last_hidden_state"""].numpy() lowercase_ = 0 else: lowercase_ = after_outputs["""logits"""].numpy() lowercase_ = 0 lowercase_ = np.amax(np.abs(out_a - out_a)) self.assertLessEqual(snake_case__ , 1E-5) def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" np.random.seed(2) lowercase_ , lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ = int((config.image_size // config.patch_size) ** 2) lowercase_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) for model_class in self.all_model_classes: lowercase_ = model_class(snake_case__) lowercase_ = self._prepare_for_class(snake_case__ , snake_case__) lowercase_ = model(snake_case__ , noise=snake_case__) lowercase_ = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(snake_case__) lowercase_ = model_class.from_config(model.get_config()) # make sure it also accepts a normal config lowercase_ = model_class.from_config(model.config) lowercase_ = new_model(snake_case__) # Build model new_model.set_weights(model.get_weights()) lowercase_ = new_model(snake_case__ , noise=snake_case__) self.assert_outputs_same(snake_case__ , snake_case__) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""") def _UpperCAmelCase ( self : int): """simple docstring""" pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""") def _UpperCAmelCase ( self : List[str]): """simple docstring""" pass @slow def _UpperCAmelCase ( self : List[Any]): """simple docstring""" lowercase_ = TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224""") self.assertIsNotNone(snake_case__) def _SCREAMING_SNAKE_CASE () -> str: '''simple docstring''' lowercase_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def _UpperCAmelCase ( self : List[Any]): """simple docstring""" return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""") if is_vision_available() else None @slow def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" np.random.seed(2) lowercase_ = TFViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""") lowercase_ = self.default_image_processor lowercase_ = prepare_img() lowercase_ = image_processor(images=snake_case__ , return_tensors="""tf""") # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowercase_ = ViTMAEConfig() lowercase_ = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2) lowercase_ = np.random.uniform(size=(1, num_patches)) # forward pass lowercase_ = model(**snake_case__ , noise=snake_case__) # verify the logits lowercase_ = tf.convert_to_tensor([1, 1_9_6, 7_6_8]) self.assertEqual(outputs.logits.shape , snake_case__) lowercase_ = tf.convert_to_tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]]) tf.debugging.assert_near(outputs.logits[0, :3, :3] , snake_case__ , atol=1E-4)
567
"""simple docstring""" from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=13 , snake_case__=30 , snake_case__=2 , snake_case__=3 , snake_case__=True , snake_case__=True , snake_case__=32 , snake_case__=2 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=10 , snake_case__=0.02 , snake_case__=3 , snake_case__=None , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase = (image_size // patch_size) ** 2 UpperCAmelCase = num_patches + 1 def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" return ViTConfig( 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=snake_case__ , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = TFViTModel(config=snake_case__ ) UpperCAmelCase = model(snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase = self.image_size // 2 UpperCAmelCase = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) UpperCAmelCase = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.type_sequence_label_size UpperCAmelCase = TFViTForImageClassification(snake_case__ ) UpperCAmelCase = model(snake_case__ , labels=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase = self.image_size // 2 UpperCAmelCase = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase = 1 UpperCAmelCase = TFViTForImageClassification(snake_case__ ) UpperCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase = model(snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Optional[int] = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () _A : Optional[Any] = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) _A : Optional[int] = False _A : Any = False _A : List[str] = False def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = TFViTModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=37 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , tf.keras.layers.Layer ) ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) UpperCAmelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case__ ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) @slow def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(snake_case__ ) def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCamelCase_ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=snake_case__ , return_tensors="""tf""" ) # forward pass UpperCAmelCase = model(**snake_case__ ) # verify the logits UpperCAmelCase = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , snake_case__ ) UpperCAmelCase = tf.constant([-0.2_744, 0.8_215, -0.0_836] ) tf.debugging.assert_near(outputs.logits[0, :3] , snake_case__ , atol=1e-4 )
673
0
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version UpperCamelCase__ : int = version.parse(importlib_metadata.version('''nltk''')) if NLTK_VERSION >= version.Version('''3.6.4'''): from nltk import word_tokenize UpperCamelCase__ : Optional[Any] = '''\ @inproceedings{banarjee2005, title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments}, author = {Banerjee, Satanjeev and Lavie, Alon}, booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization}, month = jun, year = {2005}, address = {Ann Arbor, Michigan}, publisher = {Association for Computational Linguistics}, url = {https://www.aclweb.org/anthology/W05-0909}, pages = {65--72}, } ''' UpperCamelCase__ : Union[str, Any] = '''\ METEOR, an automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations. Unigrams can be matched based on their surface forms, stemmed forms, and meanings; furthermore, METEOR can be easily extended to include more advanced matching strategies. Once all generalized unigram matches between the two strings have been found, METEOR computes a score for this matching using a combination of unigram-precision, unigram-recall, and a measure of fragmentation that is designed to directly capture how well-ordered the matched words in the machine translation are in relation to the reference. METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic data and 0.331 on the Chinese data. This is shown to be an improvement on using simply unigram-precision, unigram-recall and their harmonic F1 combination. ''' UpperCamelCase__ : Tuple = ''' Computes METEOR score of translated segments against one or more references. Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. alpha: Parameter for controlling relative weights of precision and recall. default: 0.9 beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3 gamma: Relative weight assigned to fragmentation penalty. default: 0.5 Returns: \'meteor\': meteor score. Examples: >>> meteor = datasets.load_metric(\'meteor\') >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"] >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"] >>> results = meteor.compute(predictions=predictions, references=references) >>> print(round(results["meteor"], 4)) 0.6944 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCamelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase__ ( self : str ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"""] , reference_urls=[ """https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score""", """https://en.wikipedia.org/wiki/METEOR""", ] , ) def UpperCamelCase__ ( self : List[str] , lowerCAmelCase__ : List[str] ): """simple docstring""" import nltk nltk.download("""wordnet""" ) if NLTK_VERSION >= version.Version("""3.6.5""" ): nltk.download("""punkt""" ) if NLTK_VERSION >= version.Version("""3.6.6""" ): nltk.download("""omw-1.4""" ) def UpperCamelCase__ ( self : str , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict=0.9 , lowerCAmelCase__ : int=3 , lowerCAmelCase__ : Union[str, Any]=0.5 ): """simple docstring""" if NLTK_VERSION >= version.Version("""3.6.5""" ): __SCREAMING_SNAKE_CASE : List[Any] = [ meteor_score.single_meteor_score( word_tokenize(snake_case__ ) , word_tokenize(snake_case__ ) , alpha=snake_case__ , beta=snake_case__ , gamma=snake_case__ ) for ref, pred in zip(snake_case__ , snake_case__ ) ] else: __SCREAMING_SNAKE_CASE : Optional[int] = [ meteor_score.single_meteor_score(snake_case__ , snake_case__ , alpha=snake_case__ , beta=snake_case__ , gamma=snake_case__ ) for ref, pred in zip(snake_case__ , snake_case__ ) ] return {"meteor": np.mean(snake_case__ )}
578
"""simple docstring""" import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=13 , snake_case__=7 , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=99 , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=5_12 , snake_case__=16 , snake_case__=2 , snake_case__=0.02 , snake_case__=3 , snake_case__=4 , snake_case__=None , ) -> int: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case__ , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> List[str]: """simple docstring""" UpperCAmelCase = NystromformerModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ ) UpperCAmelCase = model(snake_case__ , token_type_ids=snake_case__ ) UpperCAmelCase = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = NystromformerForMaskedLM(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = NystromformerForQuestionAnswering(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = NystromformerForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = NystromformerForTokenClassification(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = self.num_choices UpperCAmelCase = NystromformerForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Optional[Any] = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) _A : Optional[Any] = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) _A : int = False _A : Dict = False def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = NystromformerModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=snake_case__ , hidden_size=37 ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase = type self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case__ ) def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case__ ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case__ ) def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case__ ) @slow def UpperCamelCase_ ( self ) -> int: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = NystromformerModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): UpperCAmelCase = model(snake_case__ )[0] UpperCAmelCase = torch.Size((1, 6, 7_68) ) self.assertEqual(output.shape , snake_case__ ) UpperCAmelCase = torch.tensor( [[[-0.4_532, -0.0_936, 0.5_137], [-0.2_676, 0.0_628, 0.6_186], [-0.3_629, -0.1_726, 0.4_716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) ) @slow def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = """the [MASK] of Belgium is Brussels""" UpperCAmelCase = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = tokenizer(snake_case__ , return_tensors="""pt""" ) with torch.no_grad(): UpperCAmelCase = model(encoding.input_ids ).logits UpperCAmelCase = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(snake_case__ ) , """capital""" )
673
0
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _UpperCAmelCase ( a_): def __init__( self : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : int , lowercase_ : Union[str, Any] = None , ): super().__init__() self.register_modules(transformer=snake_case__ , vae=snake_case__ , scheduler=snake_case__ ) # create a imagenet -> id dictionary for easier use snake_case_ : Tuple = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(''',''' ): snake_case_ : List[Any] = int(snake_case__ ) snake_case_ : Dict = dict(sorted(self.labels.items() ) ) def _snake_case ( self : Tuple , lowercase_ : List[str] ): if not isinstance(snake_case__ , snake_case__ ): snake_case_ : Dict = list(snake_case__ ) for l in label: if l not in self.labels: raise ValueError( f"{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}." ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self : List[Any] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] = 4.0 , lowercase_ : Any = None , lowercase_ : Tuple = 50 , lowercase_ : List[str] = "pil" , lowercase_ : Dict = True , ): snake_case_ : int = len(snake_case__ ) snake_case_ : int = self.transformer.config.sample_size snake_case_ : Union[str, Any] = self.transformer.config.in_channels snake_case_ : Dict = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=snake_case__ , device=self.device , dtype=self.transformer.dtype , ) snake_case_ : Any = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents snake_case_ : Any = torch.tensor(snake_case__ , device=self.device ).reshape(-1 ) snake_case_ : int = torch.tensor([1000] * batch_size , device=self.device ) snake_case_ : Optional[Any] = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(snake_case__ ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: snake_case_ : List[Any] = latent_model_input[: len(snake_case__ ) // 2] snake_case_ : Optional[Any] = torch.cat([half, half] , dim=0 ) snake_case_ : str = self.scheduler.scale_model_input(snake_case__ , snake_case__ ) snake_case_ : Tuple = t if not torch.is_tensor(snake_case__ ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) snake_case_ : Optional[int] = latent_model_input.device.type == '''mps''' if isinstance(snake_case__ , snake_case__ ): snake_case_ : str = torch.floataa if is_mps else torch.floataa else: snake_case_ : List[str] = torch.intaa if is_mps else torch.intaa snake_case_ : Optional[Any] = torch.tensor([timesteps] , dtype=snake_case__ , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: snake_case_ : str = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML snake_case_ : Optional[int] = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output snake_case_ : str = self.transformer( snake_case__ , timestep=snake_case__ , class_labels=snake_case__ ).sample # perform guidance if guidance_scale > 1: snake_case_, snake_case_ : Any = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] snake_case_, snake_case_ : List[Any] = torch.split(snake_case__ , len(snake_case__ ) // 2 , dim=0 ) snake_case_ : Tuple = uncond_eps + guidance_scale * (cond_eps - uncond_eps) snake_case_ : str = torch.cat([half_eps, half_eps] , dim=0 ) snake_case_ : Any = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: snake_case_, snake_case_ : List[str] = torch.split(snake_case__ , snake_case__ , dim=1 ) else: snake_case_ : List[Any] = noise_pred # compute previous image: x_t -> x_t-1 snake_case_ : List[str] = self.scheduler.step(snake_case__ , snake_case__ , snake_case__ ).prev_sample if guidance_scale > 1: snake_case_, snake_case_ : Tuple = latent_model_input.chunk(2 , dim=0 ) else: snake_case_ : Optional[Any] = latent_model_input snake_case_ : Tuple = 1 / self.vae.config.scaling_factor * latents snake_case_ : List[str] = self.vae.decode(snake_case__ ).sample snake_case_ : Tuple = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 snake_case_ : Tuple = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case_ : Any = self.numpy_to_pil(snake_case__ ) if not return_dict: return (samples,) return ImagePipelineOutput(images=snake_case__ )
123
"""simple docstring""" import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Optional[int] = False def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' return TrainCommand(lowerCAmelCase ) class UpperCamelCase_ ( a_ ): @staticmethod def UpperCamelCase_ ( snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = parser.add_parser("""train""" , help="""CLI tool to train a model on a task.""" ) train_parser.add_argument( """--train_data""" , type=snake_case__ , required=snake_case__ , help="""path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.""" , ) train_parser.add_argument( """--column_label""" , type=snake_case__ , default=0 , help="""Column of the dataset csv file with example labels.""" ) train_parser.add_argument( """--column_text""" , type=snake_case__ , default=1 , help="""Column of the dataset csv file with example texts.""" ) train_parser.add_argument( """--column_id""" , type=snake_case__ , default=2 , help="""Column of the dataset csv file with example ids.""" ) train_parser.add_argument( """--skip_first_row""" , action="""store_true""" , help="""Skip the first row of the csv file (headers).""" ) train_parser.add_argument("""--validation_data""" , type=snake_case__ , default="""""" , help="""path to validation dataset.""" ) train_parser.add_argument( """--validation_split""" , type=snake_case__ , default=0.1 , help="""if validation dataset is not provided, fraction of train dataset to use as validation dataset.""" , ) train_parser.add_argument("""--output""" , type=snake_case__ , default="""./""" , help="""path to saved the trained model.""" ) train_parser.add_argument( """--task""" , type=snake_case__ , default="""text_classification""" , help="""Task to train the model on.""" ) train_parser.add_argument( """--model""" , type=snake_case__ , default="""bert-base-uncased""" , help="""Model's name or path to stored model.""" ) train_parser.add_argument("""--train_batch_size""" , type=snake_case__ , default=32 , help="""Batch size for training.""" ) train_parser.add_argument("""--valid_batch_size""" , type=snake_case__ , default=64 , help="""Batch size for validation.""" ) train_parser.add_argument("""--learning_rate""" , type=snake_case__ , default=3e-5 , help="""Learning rate.""" ) train_parser.add_argument("""--adam_epsilon""" , type=snake_case__ , default=1e-08 , help="""Epsilon for Adam optimizer.""" ) train_parser.set_defaults(func=snake_case__ ) def __init__( self , snake_case__ ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = logging.get_logger("""transformers-cli/training""" ) UpperCAmelCase = """tf""" if is_tf_available() else """torch""" os.makedirs(args.output , exist_ok=snake_case__ ) UpperCAmelCase = args.output UpperCAmelCase = args.column_label UpperCAmelCase = args.column_text UpperCAmelCase = args.column_id self.logger.info(f'''Loading {args.task} pipeline for {args.model}''' ) if args.task == "text_classification": UpperCAmelCase = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'''Loading dataset from {args.train_data}''' ) UpperCAmelCase = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) UpperCAmelCase = None if args.validation_data: self.logger.info(f'''Loading validation dataset from {args.validation_data}''' ) UpperCAmelCase = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) UpperCAmelCase = args.validation_split UpperCAmelCase = args.train_batch_size UpperCAmelCase = args.valid_batch_size UpperCAmelCase = args.learning_rate UpperCAmelCase = args.adam_epsilon def UpperCamelCase_ ( self ) -> Any: """simple docstring""" if self.framework == "tf": return self.run_tf() return self.run_torch() def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" raise NotImplementedError def UpperCamelCase_ ( self ) -> str: """simple docstring""" self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
673
0
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class __lowerCamelCase ( unittest.TestCase , a_ ): '''simple docstring''' def a_ ( self ): __SCREAMING_SNAKE_CASE : str = load_tool("text-classification" ) self.tool.setup() __SCREAMING_SNAKE_CASE : str = load_tool("text-classification" , remote=snake_case__ ) def a_ ( self ): __SCREAMING_SNAKE_CASE : int = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(snake_case__ , "positive" ) def a_ ( self ): __SCREAMING_SNAKE_CASE : Dict = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(snake_case__ , "positive" ) def a_ ( self ): __SCREAMING_SNAKE_CASE : Any = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(snake_case__ , "positive" ) def a_ ( self ): __SCREAMING_SNAKE_CASE : Any = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(snake_case__ , "positive" )
211
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=sys.maxsize ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = """bilinear""" UpperCAmelCase = max_size UpperCAmelCase = short_edge_length def __call__( self , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = [] for img in imgs: UpperCAmelCase , UpperCAmelCase = img.shape[:2] # later: provide list and randomly choose index for resize UpperCAmelCase = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img UpperCAmelCase = size * 1.0 / min(snake_case__ , snake_case__ ) if h < w: UpperCAmelCase , UpperCAmelCase = size, scale * w else: UpperCAmelCase , UpperCAmelCase = scale * h, size if max(snake_case__ , snake_case__ ) > self.max_size: UpperCAmelCase = self.max_size * 1.0 / max(snake_case__ , snake_case__ ) UpperCAmelCase = newh * scale UpperCAmelCase = neww * scale UpperCAmelCase = int(neww + 0.5 ) UpperCAmelCase = int(newh + 0.5 ) if img.dtype == np.uinta: UpperCAmelCase = Image.fromarray(snake_case__ ) UpperCAmelCase = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) UpperCAmelCase = np.asarray(snake_case__ ) else: UpperCAmelCase = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw UpperCAmelCase = nn.functional.interpolate( snake_case__ , (newh, neww) , mode=self.interp_method , align_corners=snake_case__ ).squeeze(0 ) img_augs.append(snake_case__ ) return img_augs class UpperCamelCase_ : def __init__( self , snake_case__ ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) UpperCAmelCase = cfg.INPUT.FORMAT UpperCAmelCase = cfg.SIZE_DIVISIBILITY UpperCAmelCase = cfg.PAD_VALUE UpperCAmelCase = cfg.INPUT.MAX_SIZE_TEST UpperCAmelCase = cfg.MODEL.DEVICE UpperCAmelCase = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) UpperCAmelCase = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) UpperCAmelCase = lambda snake_case__ : (x - self.pixel_mean) / self.pixel_std def UpperCamelCase_ ( self , snake_case__ ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = tuple(max(snake_case__ ) for s in zip(*[img.shape for img in images] ) ) UpperCAmelCase = [im.shape[-2:] for im in images] UpperCAmelCase = [ nn.functional.pad( snake_case__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(snake_case__ , snake_case__ ) ] return torch.stack(snake_case__ ), torch.tensor(snake_case__ ) def __call__( self , snake_case__ , snake_case__=False ) -> Optional[Any]: """simple docstring""" with torch.no_grad(): if not isinstance(snake_case__ , snake_case__ ): UpperCAmelCase = [images] if single_image: assert len(snake_case__ ) == 1 for i in range(len(snake_case__ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(snake_case__ , images.pop(snake_case__ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( snake_case__ , torch.as_tensor(img_tensorize(images.pop(snake_case__ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge UpperCAmelCase = torch.tensor([im.shape[:2] for im in images] ) UpperCAmelCase = self.aug(snake_case__ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic UpperCAmelCase = [self.normalizer(snake_case__ ) for x in images] # now pad them to do the following operations UpperCAmelCase , UpperCAmelCase = self.pad(snake_case__ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad UpperCAmelCase = torch.true_divide(snake_case__ , snake_case__ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' assert torch.isfinite(lowerCAmelCase ).all(), "Box tensor contains infinite or NaN!" UpperCAmelCase , UpperCAmelCase = box_size tensor[:, 0].clamp_(min=0 , max=lowerCAmelCase ) tensor[:, 1].clamp_(min=0 , max=lowerCAmelCase ) tensor[:, 2].clamp_(min=0 , max=lowerCAmelCase ) tensor[:, 3].clamp_(min=0 , max=lowerCAmelCase )
673
0
'''simple docstring''' import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class UpperCAmelCase ( a_ , unittest.TestCase ): '''simple docstring''' pass @nightly @require_onnxruntime @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @property def _lowerCAmelCase( self ) -> Dict: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _lowerCAmelCase( self ) -> Tuple: lowercase__ : Optional[int] = ort.SessionOptions() lowercase__ : List[Any] = False return options def _lowerCAmelCase( self ) -> str: lowercase__ : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) lowercase__ : List[str] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) lowercase__ : List[Any] = OnnxStableDiffusionInpaintPipeline.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=snake_case__ ) lowercase__ : List[Any] = '''A red cat sitting on a park bench''' lowercase__ : Dict = np.random.RandomState(0 ) lowercase__ : Optional[Any] = pipe( prompt=snake_case__ , image=snake_case__ , mask_image=snake_case__ , guidance_scale=7.5 , num_inference_steps=10 , generator=snake_case__ , output_type='''np''' , ) lowercase__ : List[Any] = output.images lowercase__ : Optional[int] = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) lowercase__ : List[str] = np.array([0.2_5_1_4, 0.3_0_0_7, 0.3_5_1_7, 0.1_7_9_0, 0.2_3_8_2, 0.3_1_6_7, 0.1_9_4_4, 0.2_2_7_3, 0.2_4_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _lowerCAmelCase( self ) -> Dict: lowercase__ : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) lowercase__ : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) lowercase__ : int = LMSDiscreteScheduler.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , subfolder='''scheduler''' , revision='''onnx''' ) lowercase__ : str = OnnxStableDiffusionInpaintPipeline.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , scheduler=snake_case__ , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=snake_case__ ) lowercase__ : Optional[int] = '''A red cat sitting on a park bench''' lowercase__ : Dict = np.random.RandomState(0 ) lowercase__ : Optional[int] = pipe( prompt=snake_case__ , image=snake_case__ , mask_image=snake_case__ , guidance_scale=7.5 , num_inference_steps=20 , generator=snake_case__ , output_type='''np''' , ) lowercase__ : str = output.images lowercase__ : Optional[int] = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) lowercase__ : Optional[Any] = np.array([0.0_0_8_6, 0.0_0_7_7, 0.0_0_8_3, 0.0_0_9_3, 0.0_1_0_7, 0.0_1_3_9, 0.0_0_9_4, 0.0_0_9_7, 0.0_1_2_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
152
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase_ : List[str] = logging.get_logger(__name__) def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase=False ): '''simple docstring''' UpperCAmelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''deit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''deit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''deit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''deit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''deit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''deit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''deit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''deit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''deit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''deit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" UpperCAmelCase = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: UpperCAmelCase = """""" else: UpperCAmelCase = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) UpperCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[ : config.hidden_size, : ] UpperCAmelCase = in_proj_bias[: config.hidden_size] UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = dct.pop(lowerCAmelCase ) UpperCAmelCase = val def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCAmelCase = Image.open(requests.get(lowerCAmelCase , stream=lowerCAmelCase ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = DeiTConfig() # all deit models have fine-tuned heads UpperCAmelCase = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size UpperCAmelCase = 1000 UpperCAmelCase = """huggingface/label-files""" UpperCAmelCase = """imagenet-1k-id2label.json""" UpperCAmelCase = json.load(open(hf_hub_download(lowerCAmelCase , lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) UpperCAmelCase = {int(lowerCAmelCase ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} UpperCAmelCase = int(deit_name[-6:-4] ) UpperCAmelCase = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): UpperCAmelCase = 192 UpperCAmelCase = 768 UpperCAmelCase = 12 UpperCAmelCase = 3 elif deit_name[9:].startswith("""small""" ): UpperCAmelCase = 384 UpperCAmelCase = 1536 UpperCAmelCase = 12 UpperCAmelCase = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): UpperCAmelCase = 1024 UpperCAmelCase = 4096 UpperCAmelCase = 24 UpperCAmelCase = 16 # load original model from timm UpperCAmelCase = timm.create_model(lowerCAmelCase , pretrained=lowerCAmelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys UpperCAmelCase = timm_model.state_dict() UpperCAmelCase = create_rename_keys(lowerCAmelCase , lowerCAmelCase ) for src, dest in rename_keys: rename_key(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) read_in_q_k_v(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # load HuggingFace model UpperCAmelCase = DeiTForImageClassificationWithTeacher(lowerCAmelCase ).eval() model.load_state_dict(lowerCAmelCase ) # Check outputs on an image, prepared by DeiTImageProcessor UpperCAmelCase = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 UpperCAmelCase = DeiTImageProcessor(size=lowerCAmelCase , crop_size=config.image_size ) UpperCAmelCase = image_processor(images=prepare_img() , return_tensors="""pt""" ) UpperCAmelCase = encoding["""pixel_values"""] UpperCAmelCase = model(lowerCAmelCase ) UpperCAmelCase = timm_model(lowerCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase , outputs.logits , atol=1e-3 ) Path(lowerCAmelCase ).mkdir(exist_ok=lowerCAmelCase ) print(F'''Saving model {deit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCAmelCase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowerCAmelCase ) if __name__ == "__main__": lowerCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) lowerCAmelCase_ : str = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
673
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() __lowercase : List[str] = logging.get_logger(__name__) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str]=False ): __a : Tuple = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""deit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""deit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""deit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""deit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""deit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""deit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""deit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""deit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""deit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""deit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'deit.embeddings.cls_token'), ('dist_token', 'deit.embeddings.distillation_token'), ('patch_embed.proj.weight', 'deit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'deit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'deit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" __a : Any = [(pair[0], pair[1][4:]) if pair[1].startswith('deit' ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ('norm.weight', 'deit.layernorm.weight'), ('norm.bias', 'deit.layernorm.bias'), ('head.weight', 'cls_classifier.weight'), ('head.bias', 'cls_classifier.bias'), ('head_dist.weight', 'distillation_classifier.weight'), ('head_dist.bias', 'distillation_classifier.bias'), ] ) return rename_keys def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str=False ): for i in range(config.num_hidden_layers ): if base_model: __a : Union[str, Any] = '' else: __a : List[Any] = 'deit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __a : Tuple = state_dict.pop(F"""blocks.{i}.attn.qkv.weight""" ) __a : List[str] = state_dict.pop(F"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict __a : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] __a : List[str] = in_proj_bias[: config.hidden_size] __a : Dict = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __a : str = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __a : List[str] = in_proj_weight[ -config.hidden_size :, : ] __a : Optional[Any] = in_proj_bias[-config.hidden_size :] def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] ): __a : Optional[int] = dct.pop(_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = val def lowerCamelCase (): __a : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' __a : Optional[int] = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : Optional[int] = DeiTConfig() # all deit models have fine-tuned heads __a : int = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size __a : str = 1_000 __a : Tuple = 'huggingface/label-files' __a : Optional[int] = 'imagenet-1k-id2label.json' __a : Dict = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) __a : Dict = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __a : Optional[Any] = idalabel __a : Any = {v: k for k, v in idalabel.items()} __a : Optional[int] = int(deit_name[-6:-4] ) __a : Tuple = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith('tiny' ): __a : str = 192 __a : str = 768 __a : Union[str, Any] = 12 __a : Tuple = 3 elif deit_name[9:].startswith('small' ): __a : Dict = 384 __a : Optional[int] = 1_536 __a : Tuple = 12 __a : Tuple = 6 if deit_name[9:].startswith('base' ): pass elif deit_name[4:].startswith('large' ): __a : List[str] = 1_024 __a : str = 4_096 __a : Optional[Any] = 24 __a : List[str] = 16 # load original model from timm __a : Any = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys __a : Optional[int] = timm_model.state_dict() __a : List[str] = create_rename_keys(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # load HuggingFace model __a : int = DeiTForImageClassificationWithTeacher(_SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by DeiTImageProcessor __a : List[Any] = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 __a : List[str] = DeiTImageProcessor(size=_SCREAMING_SNAKE_CASE , crop_size=config.image_size ) __a : Optional[int] = image_processor(images=prepare_img() , return_tensors='pt' ) __a : Dict = encoding['pixel_values'] __a : Optional[int] = model(_SCREAMING_SNAKE_CASE ) __a : int = timm_model(_SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_SCREAMING_SNAKE_CASE , outputs.logits , atol=1e-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(F"""Saving model {deit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--deit_name', default='vit_deit_base_distilled_patch16_224', type=str, help='Name of the DeiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __lowercase : str = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
476
"""simple docstring""" import unittest from typing import Dict, List, Optional, Union 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 BridgeTowerImageProcessor class UpperCamelCase_ ( unittest.TestCase ): def __init__( self , snake_case__ , snake_case__ = True , snake_case__ = None , snake_case__ = 32 , snake_case__ = True , snake_case__ = 1 / 2_55 , snake_case__ = True , snake_case__ = True , snake_case__ = [0.48_145_466, 0.4_578_275, 0.40_821_073] , snake_case__ = [0.26_862_954, 0.26_130_258, 0.27_577_711] , snake_case__ = True , snake_case__=7 , snake_case__=30 , snake_case__=4_00 , snake_case__=3 , ) -> List[str]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = do_resize UpperCAmelCase = size if size is not None else {"""shortest_edge""": 2_88} UpperCAmelCase = size_divisor UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = do_normalize UpperCAmelCase = do_center_crop UpperCAmelCase = image_mean UpperCAmelCase = image_std UpperCAmelCase = do_pad UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def UpperCamelCase_ ( self , snake_case__ , snake_case__=False ) -> int: """simple docstring""" if not batched: UpperCAmelCase = self.size["""shortest_edge"""] UpperCAmelCase = image_inputs[0] if isinstance(snake_case__ , Image.Image ): UpperCAmelCase , UpperCAmelCase = image.size else: UpperCAmelCase , UpperCAmelCase = image.shape[1], image.shape[2] UpperCAmelCase = size / min(snake_case__ , snake_case__ ) if h < w: UpperCAmelCase , UpperCAmelCase = size, scale * w else: UpperCAmelCase , UpperCAmelCase = scale * h, size UpperCAmelCase = int((13_33 / 8_00) * size ) if max(snake_case__ , snake_case__ ) > max_size: UpperCAmelCase = max_size / max(snake_case__ , snake_case__ ) UpperCAmelCase = newh * scale UpperCAmelCase = neww * scale UpperCAmelCase , UpperCAmelCase = int(newh + 0.5 ), int(neww + 0.5 ) UpperCAmelCase , UpperCAmelCase = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: UpperCAmelCase = [] for image in image_inputs: UpperCAmelCase , UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCAmelCase = max(snake_case__ , key=lambda snake_case__ : item[0] )[0] UpperCAmelCase = max(snake_case__ , key=lambda snake_case__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : List[Any] = BridgeTowerImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = BridgeTowerImageProcessingTester(self ) @property def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case__ , """image_mean""" ) ) self.assertTrue(hasattr(snake_case__ , """image_std""" ) ) self.assertTrue(hasattr(snake_case__ , """do_normalize""" ) ) self.assertTrue(hasattr(snake_case__ , """do_resize""" ) ) self.assertTrue(hasattr(snake_case__ , """size""" ) ) self.assertTrue(hasattr(snake_case__ , """size_divisor""" ) ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , Image.Image ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , numpify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , np.ndarray ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , torchify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , torch.Tensor ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(snake_case__ , return_tensors="""pt""" ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
673
0
import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input A_ = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def UpperCAmelCase ( )-> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_ = _ask_options( '''In which compute environment are you running?''' ,['''This machine''', '''AWS (Amazon SageMaker)'''] ,_convert_compute_environment ,) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: SCREAMING_SNAKE_CASE_ = get_sagemaker_input() else: SCREAMING_SNAKE_CASE_ = get_cluster_input() return config def UpperCAmelCase ( UpperCAmelCase=None )-> Optional[Any]: '''simple docstring''' if subparsers is not None: SCREAMING_SNAKE_CASE_ = subparsers.add_parser('''config''' ,description=UpperCAmelCase ) else: SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser('''Accelerate config command''' ,description=UpperCAmelCase ) parser.add_argument( '''--config_file''' ,default=UpperCAmelCase ,help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) ,) if subparsers is not None: parser.set_defaults(func=UpperCAmelCase ) return parser def UpperCAmelCase ( UpperCAmelCase )-> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_ = get_user_input() if args.config_file is not None: SCREAMING_SNAKE_CASE_ = args.config_file else: if not os.path.isdir(UpperCAmelCase ): os.makedirs(UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(UpperCAmelCase ) else: config.to_yaml_file(UpperCAmelCase ) print(f'''accelerate configuration saved at {config_file}''' ) def UpperCAmelCase ( )-> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ = config_command_parser() SCREAMING_SNAKE_CASE_ = parser.parse_args() config_command(UpperCAmelCase ) if __name__ == "__main__": main()
393
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : Any = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : List[str] = XLMRobertaTokenizer _A : List[str] = XLMRobertaTokenizerFast _A : Optional[Any] = True _A : List[str] = True def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XLMRobertaTokenizer(snake_case__ , keep_accents=snake_case__ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = """<pad>""" UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__ ) , snake_case__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__ ) , snake_case__ ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(snake_case__ ) , 10_02 ) def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = XLMRobertaTokenizer(snake_case__ , keep_accents=snake_case__ ) UpperCAmelCase = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(snake_case__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) UpperCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( snake_case__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(snake_case__ ) self.assertListEqual( snake_case__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(snake_case__ ) self.assertListEqual( snake_case__ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return UpperCAmelCase = (self.rust_tokenizer_class, """hf-internal-testing/tiny-xlm-roberta""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) UpperCAmelCase = self.tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.save_pretrained(snake_case__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) UpperCAmelCase = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(snake_case__ , snake_case__ ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(snake_case__ ) # Save tokenizer rust, legacy_format=True UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(snake_case__ , legacy_format=snake_case__ ) UpperCAmelCase = tokenizer_p.save_pretrained(snake_case__ ) # Checks it save with the same files self.assertSequenceEqual(snake_case__ , snake_case__ ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) shutil.rmtree(snake_case__ ) # Save tokenizer rust, legacy_format=False UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(snake_case__ , legacy_format=snake_case__ ) UpperCAmelCase = tokenizer_p.save_pretrained(snake_case__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(snake_case__ ) UpperCAmelCase = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) shutil.rmtree(snake_case__ ) @cached_property def UpperCamelCase_ ( self ) -> int: """simple docstring""" return XLMRobertaTokenizer.from_pretrained("""xlm-roberta-base""" ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" with tempfile.NamedTemporaryFile() as f: shutil.copyfile(snake_case__ , f.name ) UpperCAmelCase = XLMRobertaTokenizer(f.name , keep_accents=snake_case__ ) UpperCAmelCase = pickle.dumps(snake_case__ ) pickle.loads(snake_case__ ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" if not self.test_rust_tokenizer: return UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = """I was born in 92000, and this is falsé.""" UpperCAmelCase = tokenizer.tokenize(snake_case__ ) UpperCAmelCase = rust_tokenizer.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) UpperCAmelCase = tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) UpperCAmelCase = rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = tokenizer.encode(snake_case__ ) UpperCAmelCase = rust_tokenizer.encode(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) @slow def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = """Hello World!""" UpperCAmelCase = [0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(snake_case__ , self.big_tokenizer.encode(snake_case__ ) ) @slow def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) UpperCAmelCase = [ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(snake_case__ , self.big_tokenizer.encode(snake_case__ ) ) @slow def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = {"""input_ids""": [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=snake_case__ , model_name="""xlm-roberta-base""" , revision="""d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3""" , )
673
0
import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging __UpperCAmelCase = logging.get_logger(__name__) class lowerCamelCase (a_ ): '''simple docstring''' _snake_case : List[str] = 'linear' _snake_case : Union[str, Any] = 'cosine' _snake_case : Dict = 'cosine_with_restarts' _snake_case : List[Any] = 'polynomial' _snake_case : int = 'constant' _snake_case : Optional[int] = 'constant_with_warmup' _snake_case : str = 'piecewise_constant' def lowercase__ ( __snake_case : str , __snake_case : Tuple = -1 ): '''simple docstring''' return LambdaLR(__snake_case , lambda __snake_case : 1 , last_epoch=__snake_case ) def lowercase__ ( __snake_case : List[str] , __snake_case : Optional[int] , __snake_case : Optional[Any] = -1 ): '''simple docstring''' def lr_lambda(__snake_case : List[Any] ): if current_step < num_warmup_steps: return float(__snake_case ) / float(max(1.0 , __snake_case ) ) return 1.0 return LambdaLR(__snake_case , __snake_case , last_epoch=__snake_case ) def lowercase__ ( __snake_case : Any , __snake_case : Any , __snake_case : int = -1 ): '''simple docstring''' UpperCAmelCase_ : List[str] = {} UpperCAmelCase_ : int = step_rules.split(',' ) for rule_str in rule_list[:-1]: UpperCAmelCase_ , UpperCAmelCase_ : str = rule_str.split(':' ) UpperCAmelCase_ : Any = int(__snake_case ) UpperCAmelCase_ : List[str] = float(__snake_case ) UpperCAmelCase_ : Dict = value UpperCAmelCase_ : str = float(rule_list[-1] ) def create_rules_function(__snake_case : Tuple , __snake_case : Dict ): def rule_func(__snake_case : Dict ) -> float: UpperCAmelCase_ : Union[str, Any] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(__snake_case ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func UpperCAmelCase_ : Dict = create_rules_function(__snake_case , __snake_case ) return LambdaLR(__snake_case , __snake_case , last_epoch=__snake_case ) def lowercase__ ( __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : int , __snake_case : int=-1 ): '''simple docstring''' def lr_lambda(__snake_case : Optional[int] ): if current_step < num_warmup_steps: return float(__snake_case ) / float(max(1 , __snake_case ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(__snake_case , __snake_case , __snake_case ) def lowercase__ ( __snake_case : List[str] , __snake_case : Tuple , __snake_case : Optional[Any] , __snake_case : List[str] = 0.5 , __snake_case : List[str] = -1 ): '''simple docstring''' def lr_lambda(__snake_case : Optional[int] ): if current_step < num_warmup_steps: return float(__snake_case ) / float(max(1 , __snake_case ) ) UpperCAmelCase_ : Tuple = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(__snake_case ) * 2.0 * progress )) ) return LambdaLR(__snake_case , __snake_case , __snake_case ) def lowercase__ ( __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Dict , __snake_case : int = 1 , __snake_case : List[str] = -1 ): '''simple docstring''' def lr_lambda(__snake_case : str ): if current_step < num_warmup_steps: return float(__snake_case ) / float(max(1 , __snake_case ) ) UpperCAmelCase_ : Any = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(__snake_case ) * progress) % 1.0) )) ) return LambdaLR(__snake_case , __snake_case , __snake_case ) def lowercase__ ( __snake_case : List[str] , __snake_case : List[Any] , __snake_case : Any , __snake_case : Optional[Any]=1E-7 , __snake_case : List[str]=1.0 , __snake_case : Any=-1 ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = optimizer.defaults['lr'] if not (lr_init > lr_end): raise ValueError(F"lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})" ) def lr_lambda(__snake_case : str ): if current_step < num_warmup_steps: return float(__snake_case ) / float(max(1 , __snake_case ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: UpperCAmelCase_ : Union[str, Any] = lr_init - lr_end UpperCAmelCase_ : List[Any] = num_training_steps - num_warmup_steps UpperCAmelCase_ : Tuple = 1 - (current_step - num_warmup_steps) / decay_steps UpperCAmelCase_ : Tuple = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(__snake_case , __snake_case , __snake_case ) __UpperCAmelCase = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def lowercase__ ( __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Optional[Any] = None , __snake_case : Dict = None , __snake_case : Dict = None , __snake_case : Tuple = 1 , __snake_case : int = 1.0 , __snake_case : Any = -1 , ): '''simple docstring''' UpperCAmelCase_ : str = SchedulerType(__snake_case ) UpperCAmelCase_ : Optional[Any] = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(__snake_case , last_epoch=__snake_case ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(__snake_case , step_rules=__snake_case , last_epoch=__snake_case ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F"{name} requires `num_warmup_steps`, please provide that argument." ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(__snake_case , num_warmup_steps=__snake_case , last_epoch=__snake_case ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F"{name} requires `num_training_steps`, please provide that argument." ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( __snake_case , num_warmup_steps=__snake_case , num_training_steps=__snake_case , num_cycles=__snake_case , last_epoch=__snake_case , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( __snake_case , num_warmup_steps=__snake_case , num_training_steps=__snake_case , power=__snake_case , last_epoch=__snake_case , ) return schedule_func( __snake_case , num_warmup_steps=__snake_case , num_training_steps=__snake_case , last_epoch=__snake_case )
406
"""simple docstring""" import socket def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) UpperCAmelCase = socket.gethostname() UpperCAmelCase = 12312 sock.connect((host, port) ) sock.send(b"""Hello server!""" ) with open("""Received_file""" , """wb""" ) as out_file: print("""File opened""" ) print("""Receiving data...""" ) while True: UpperCAmelCase = sock.recv(1024 ) if not data: break out_file.write(lowerCAmelCase ) print("""Successfully received the file""" ) sock.close() print("""Connection closed""" ) if __name__ == "__main__": main()
673
0
"""simple docstring""" def __a ( A ) -> str: '''simple docstring''' A__ = [0] * len(A ) A__ = [] A__ = [1] * len(A ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(A ) ): if indegree[i] == 0: queue.append(A ) while queue: A__ = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: A__ = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(A ) print(max(A ) ) # Adjacency list of Graph __UpperCAmelCase ={0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
337
"""simple docstring""" import math def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' return math.sqrt(lowerCAmelCase ) * math.sqrt(lowerCAmelCase ) == num def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = 0 UpperCAmelCase = n while left <= right: UpperCAmelCase = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: UpperCAmelCase = mid - 1 else: UpperCAmelCase = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
673
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
546
"""simple docstring""" import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _lowerCAmelCase ( *lowerCAmelCase ): '''simple docstring''' if not isinstance(lowerCAmelCase , lowerCAmelCase ): UpperCAmelCase = list(lowerCAmelCase ) for i in range(len(lowerCAmelCase ) ): UpperCAmelCase = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(lowerCAmelCase , lowerCAmelCase ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _lowerCAmelCase ( lowerCAmelCase = None , lowerCAmelCase = 128 ): '''simple docstring''' if function is None: return functools.partial(lowerCAmelCase , starting_batch_size=lowerCAmelCase ) UpperCAmelCase = starting_batch_size def decorator(*lowerCAmelCase , **lowerCAmelCase ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() UpperCAmelCase = list(inspect.signature(lowerCAmelCase ).parameters.keys() ) # Guard against user error if len(lowerCAmelCase ) < (len(lowerCAmelCase ) + 1): UpperCAmelCase = """, """.join([F'''{arg}={value}''' for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F'''Batch size was passed into `{function.__name__}` as the first argument when called.''' F'''Remove this as the decorator already does so: `{function.__name__}({arg_str})`''' ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(lowerCAmelCase , *lowerCAmelCase , **lowerCAmelCase ) except Exception as e: if should_reduce_batch_size(lowerCAmelCase ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
673
0
import numpy as np def a_ ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = 1e-12 , SCREAMING_SNAKE_CASE__ : Any = 100 , ): '''simple docstring''' assert np.shape(SCREAMING_SNAKE_CASE__ )[0] == np.shape(SCREAMING_SNAKE_CASE__ )[1] # Ensure proper dimensionality. assert np.shape(SCREAMING_SNAKE_CASE__ )[0] == np.shape(SCREAMING_SNAKE_CASE__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(SCREAMING_SNAKE_CASE__ ) == np.iscomplexobj(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Union[str, Any] =np.iscomplexobj(SCREAMING_SNAKE_CASE__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(SCREAMING_SNAKE_CASE__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. _lowerCamelCase : Optional[int] =False _lowerCamelCase : Optional[Any] =0 _lowerCamelCase : int =0 _lowerCamelCase : Tuple =1e12 while not convergence: # Multiple matrix by the vector. _lowerCamelCase : Optional[int] =np.dot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Normalize the resulting output vector. _lowerCamelCase : str =w / np.linalg.norm(SCREAMING_SNAKE_CASE__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) _lowerCamelCase : Tuple =vector.conj().T if is_complex else vector.T _lowerCamelCase : Optional[Any] =np.dot(SCREAMING_SNAKE_CASE__ , np.dot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Check convergence. _lowerCamelCase : Optional[Any] =np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: _lowerCamelCase : Any =True _lowerCamelCase : List[str] =lambda_ if is_complex: _lowerCamelCase : int =np.real(lambda_ ) return lambda_, vector def a_ ( ): '''simple docstring''' _lowerCamelCase : Optional[int] =np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) _lowerCamelCase : Optional[Any] =np.array([41, 4, 20] ) _lowerCamelCase : str =real_input_matrix.astype(np.complexaaa ) _lowerCamelCase : Optional[Any] =np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T _lowerCamelCase : Any =np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": _lowerCamelCase : str =real_input_matrix _lowerCamelCase : int =real_vector elif problem_type == "complex": _lowerCamelCase : Dict =complex_input_matrix _lowerCamelCase : Optional[Any] =complex_vector # Our implementation. _lowerCamelCase , _lowerCamelCase : Tuple =power_iteration(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). _lowerCamelCase , _lowerCamelCase : Optional[int] =np.linalg.eigh(SCREAMING_SNAKE_CASE__ ) # Last eigenvalue is the maximum one. _lowerCamelCase : Union[str, Any] =eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. _lowerCamelCase : Tuple =eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(SCREAMING_SNAKE_CASE__ ) - np.abs(SCREAMING_SNAKE_CASE__ ) ) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
464
"""simple docstring""" import math def _lowerCAmelCase ( lowerCAmelCase = 100 ): '''simple docstring''' UpperCAmelCase = sum(i * i for i in range(1 , n + 1 ) ) UpperCAmelCase = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F'{solution() = }')
673
0
"""simple docstring""" import numpy as np def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> Tuple: '''simple docstring''' return 1 / (1 + np.exp(-vector )) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> int: '''simple docstring''' return vector * sigmoid(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
567
"""simple docstring""" def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [0] * len(lowerCAmelCase ) UpperCAmelCase = [] UpperCAmelCase = [1] * len(lowerCAmelCase ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCAmelCase ) ): if indegree[i] == 0: queue.append(lowerCAmelCase ) while queue: UpperCAmelCase = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: UpperCAmelCase = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(lowerCAmelCase ) print(max(lowerCAmelCase ) ) # Adjacency list of Graph lowerCAmelCase_ : str = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
673
0
'''simple docstring''' from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def lowerCAmelCase_ ( _lowerCamelCase: List[str] , _lowerCamelCase: List[str] , _lowerCamelCase: str = None ): if version.parse(hfh.__version__ ).release < version.parse("""0.11.0""" ).release: # old versions of hfh don't url-encode the file path __SCREAMING_SNAKE_CASE : Optional[int] = quote(_lowerCamelCase ) return hfh.hf_hub_url(_lowerCamelCase , _lowerCamelCase , repo_type="""dataset""" , revision=_lowerCamelCase )
578
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase_ ( a_ ): _A : Optional[int] = 'facebook/bart-large-mnli' _A : Union[str, Any] = ( 'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ' 'should be the text to classify, and `labels`, which should be the list of labels to use for classification. ' 'It returns the most likely label in the list of provided `labels` for the input text.' ) _A : Dict = 'text_classifier' _A : Union[str, Any] = AutoTokenizer _A : Tuple = AutoModelForSequenceClassification _A : Optional[int] = ['text', ['text']] _A : Dict = ['text'] def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" super().setup() UpperCAmelCase = self.model.config UpperCAmelCase = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): UpperCAmelCase = int(snake_case__ ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = labels return self.pre_processor( [text] * len(snake_case__ ) , [f'''This example is {label}''' for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def UpperCamelCase_ ( self , snake_case__ ) -> str: """simple docstring""" UpperCAmelCase = outputs.logits UpperCAmelCase = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
673
0
"""simple docstring""" def __lowercase ( _a ): snake_case_ : Any = int(_a ) if n_element < 1: snake_case_ : Optional[int] = ValueError('''a should be a positive number''' ) raise my_error snake_case_ : Dict = [1] snake_case_, snake_case_, snake_case_ : Tuple = (0, 0, 0) snake_case_ : List[Any] = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase__ : Dict = input('''Enter the last number (nth term) of the Hamming Number Series: ''') print('''Formula of Hamming Number Series => 2^i * 3^j * 5^k''') lowercase__ : str = hamming(int(n)) print('''-----------------------------------------------------''') print(f'The list with nth numbers is: {hamming_numbers}') print('''-----------------------------------------------------''')
123
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class UpperCamelCase_ ( a_ ): _A : Union[List[PIL.Image.Image], np.ndarray] _A : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
673
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def __A ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[str]=8 ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __SCREAMING_SNAKE_CASE : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def __A ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str=5_1_2 , _SCREAMING_SNAKE_CASE : List[Any]=5_1_2 ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __SCREAMING_SNAKE_CASE : Tuple = np.array(pil_image.convert("RGB" ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = arr.astype(np.floataa ) / 1_2_7.5 - 1 __SCREAMING_SNAKE_CASE : int = np.transpose(_SCREAMING_SNAKE_CASE , [2, 0, 1] ) __SCREAMING_SNAKE_CASE : List[str] = torch.from_numpy(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) return image class __lowerCamelCase ( a_ ): '''simple docstring''' def __init__( self , a__ , a__ , a__ , ): super().__init__() self.register_modules( unet=snake_case__ , scheduler=snake_case__ , movq=snake_case__ , ) __SCREAMING_SNAKE_CASE : List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def a_ ( self , a__ , a__ , a__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = min(int(num_inference_steps * strength ) , snake_case__ ) __SCREAMING_SNAKE_CASE : Tuple = max(num_inference_steps - init_timestep , 0 ) __SCREAMING_SNAKE_CASE : List[str] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def a_ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__=None ): if not isinstance(snake_case__ , (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(snake_case__ )}' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image.to(device=snake_case__ , dtype=snake_case__ ) __SCREAMING_SNAKE_CASE : str = batch_size * num_images_per_prompt if image.shape[1] == 4: __SCREAMING_SNAKE_CASE : Tuple = image else: if isinstance(snake_case__ , snake_case__ ) and len(snake_case__ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(snake_case__ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) elif isinstance(snake_case__ , snake_case__ ): __SCREAMING_SNAKE_CASE : Tuple = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(snake_case__ ) ] __SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(snake_case__ , dim=0 ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = self.movq.encode(snake_case__ ).latent_dist.sample(snake_case__ ) __SCREAMING_SNAKE_CASE : List[Any] = self.movq.config.scaling_factor * init_latents __SCREAMING_SNAKE_CASE : Tuple = torch.cat([init_latents] , dim=0 ) __SCREAMING_SNAKE_CASE : Any = init_latents.shape __SCREAMING_SNAKE_CASE : Any = randn_tensor(snake_case__ , generator=snake_case__ , device=snake_case__ , dtype=snake_case__ ) # get latents __SCREAMING_SNAKE_CASE : Any = self.scheduler.add_noise(snake_case__ , snake_case__ , snake_case__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = init_latents return latents def a_ ( self , a__=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.device(f'cuda:{gpu_id}' ) __SCREAMING_SNAKE_CASE : str = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(snake_case__ , snake_case__ ) def a_ ( self , a__=0 ): if is_accelerate_available() and is_accelerate_version(">=" , "0.17.0.dev0" ): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." ) __SCREAMING_SNAKE_CASE : Dict = torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=snake_case__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __SCREAMING_SNAKE_CASE : Tuple = None for cpu_offloaded_model in [self.unet, self.movq]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = cpu_offload_with_hook(snake_case__ , snake_case__ , prev_module_hook=snake_case__ ) # We'll offload the last model manually. __SCREAMING_SNAKE_CASE : Optional[Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def a_ ( self ): if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(snake_case__ , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(snake_case__ ) def __call__( self , a__ , a__ , a__ , a__ = 512 , a__ = 512 , a__ = 100 , a__ = 4.0 , a__ = 0.3 , a__ = 1 , a__ = None , a__ = "pil" , a__ = True , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self._execution_device __SCREAMING_SNAKE_CASE : Dict = guidance_scale > 1.0 if isinstance(snake_case__ , snake_case__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat(snake_case__ , dim=0 ) __SCREAMING_SNAKE_CASE : Optional[int] = image_embeds.shape[0] if isinstance(snake_case__ , snake_case__ ): __SCREAMING_SNAKE_CASE : List[str] = torch.cat(snake_case__ , dim=0 ) if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE : Optional[int] = image_embeds.repeat_interleave(snake_case__ , dim=0 ) __SCREAMING_SNAKE_CASE : List[str] = negative_image_embeds.repeat_interleave(snake_case__ , dim=0 ) __SCREAMING_SNAKE_CASE : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=snake_case__ ) if not isinstance(snake_case__ , snake_case__ ): __SCREAMING_SNAKE_CASE : Optional[int] = [image] if not all(isinstance(snake_case__ , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( f'Input is in incorrect format: {[type(snake_case__ ) for i in image]}. Currently, we only support PIL image and pytorch tensor' ) __SCREAMING_SNAKE_CASE : Any = torch.cat([prepare_image(snake_case__ , snake_case__ , snake_case__ ) for i in image] , dim=0 ) __SCREAMING_SNAKE_CASE : Any = image.to(dtype=image_embeds.dtype , device=snake_case__ ) __SCREAMING_SNAKE_CASE : Dict = self.movq.encode(snake_case__ )["latents"] __SCREAMING_SNAKE_CASE : Optional[int] = latents.repeat_interleave(snake_case__ , dim=0 ) self.scheduler.set_timesteps(snake_case__ , device=snake_case__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_timesteps(snake_case__ , snake_case__ , snake_case__ ) __SCREAMING_SNAKE_CASE : List[str] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = downscale_height_and_width(snake_case__ , snake_case__ , self.movq_scale_factor ) __SCREAMING_SNAKE_CASE : Any = self.prepare_latents( snake_case__ , snake_case__ , snake_case__ , snake_case__ , image_embeds.dtype , snake_case__ , snake_case__ ) for i, t in enumerate(self.progress_bar(snake_case__ ) ): # expand the latents if we are doing classifier free guidance __SCREAMING_SNAKE_CASE : int = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __SCREAMING_SNAKE_CASE : str = {"image_embeds": image_embeds} __SCREAMING_SNAKE_CASE : Dict = self.unet( sample=snake_case__ , timestep=snake_case__ , encoder_hidden_states=snake_case__ , added_cond_kwargs=snake_case__ , return_dict=snake_case__ , )[0] if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = noise_pred.split(latents.shape[1] , dim=1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = noise_pred.chunk(2 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = variance_pred.chunk(2 ) __SCREAMING_SNAKE_CASE : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , "variance_type" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( snake_case__ , snake_case__ , snake_case__ , generator=snake_case__ , )[0] # post-processing __SCREAMING_SNAKE_CASE : int = self.movq.decode(snake_case__ , force_not_quantize=snake_case__ )["sample"] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: __SCREAMING_SNAKE_CASE : Any = image * 0.5 + 0.5 __SCREAMING_SNAKE_CASE : Union[str, Any] = image.clamp(0 , 1 ) __SCREAMING_SNAKE_CASE : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE : List[Any] = self.numpy_to_pil(snake_case__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=snake_case__ )
211
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCAmelCase_ : Any = { '''configuration_encodec''': [ '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EncodecConfig''', ], '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EncodecModel''', '''EncodecPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
673
0
'''simple docstring''' import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib __a: List[str] = get_logger() __a: Optional[dict] = None class UpperCAmelCase ( TensorFormatter[Mapping, "jax.Array", Mapping] ): '''simple docstring''' def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , **__lowerCAmelCase ) -> int: super().__init__(features=snake_case__ ) import jax from jaxlib.xla_client import Device if isinstance(snake_case__ , snake_case__ ): raise ValueError( F"""Expected {device} to be a `str` not {type(snake_case__ )}, as `jaxlib.xla_extension.Device` """ '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround ''' '''the device with `str()` to get its string identifier that will be internally mapped ''' '''to the actual `jaxlib.xla_extension.Device`.''' ) lowercase__ : Optional[int] = device if isinstance(snake_case__ , snake_case__ ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: lowercase__ : str = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F"""Device with string identifier {self.device} not listed among the available """ F"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ F"""device: {str(jax.devices()[0] )}.""" ) lowercase__ : Union[str, Any] = str(jax.devices()[0] ) lowercase__ : Dict = jnp_array_kwargs @staticmethod def _lowerCAmelCase( ) -> Dict[str, "jaxlib.xla_extension.Device"]: import jax return {str(snake_case__ ): device for device in jax.devices()} def _lowerCAmelCase( self , __lowerCAmelCase ) -> Tuple: import jax import jax.numpy as jnp if isinstance(snake_case__ , snake_case__ ) and column: if all( isinstance(snake_case__ , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(snake_case__ , axis=0 ) return column def _lowerCAmelCase( self , __lowerCAmelCase ) -> Dict: import jax import jax.numpy as jnp if isinstance(snake_case__ , (str, bytes, type(snake_case__ )) ): return value elif isinstance(snake_case__ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() lowercase__ : Dict = {} if isinstance(snake_case__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: lowercase__ : List[str] = {'''dtype''': jnp.intaa} else: lowercase__ : Optional[int] = {'''dtype''': jnp.intaa} elif isinstance(snake_case__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): lowercase__ : List[Any] = {'''dtype''': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(snake_case__ , PIL.Image.Image ): lowercase__ : Tuple = np.asarray(snake_case__ ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: lowercase__ : Optional[Any] = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(snake_case__ , **{**default_dtype, **self.jnp_array_kwargs} ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> Any: import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(snake_case__ , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(snake_case__ , '''__array__''' ) and not isinstance(snake_case__ , jax.Array ): lowercase__ : Any = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(snake_case__ , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(snake_case__ ) for substruct in data_struct] ) elif isinstance(snake_case__ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(snake_case__ ) for substruct in data_struct] ) return self._tensorize(snake_case__ ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> int: return map_nested(self._recursive_tensorize , snake_case__ , map_list=snake_case__ ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> Mapping: lowercase__ : List[Any] = self.numpy_arrow_extractor().extract_row(snake_case__ ) lowercase__ : Optional[int] = self.python_features_decoder.decode_row(snake_case__ ) return self.recursive_tensorize(snake_case__ ) def _lowerCAmelCase( self , __lowerCAmelCase ) -> "jax.Array": lowercase__ : Any = self.numpy_arrow_extractor().extract_column(snake_case__ ) lowercase__ : Any = self.python_features_decoder.decode_column(snake_case__ , pa_table.column_names[0] ) lowercase__ : Any = self.recursive_tensorize(snake_case__ ) lowercase__ : Optional[int] = self._consolidate(snake_case__ ) return column def _lowerCAmelCase( self , __lowerCAmelCase ) -> Mapping: lowercase__ : Dict = self.numpy_arrow_extractor().extract_batch(snake_case__ ) lowercase__ : str = self.python_features_decoder.decode_batch(snake_case__ ) lowercase__ : List[Any] = self.recursive_tensorize(snake_case__ ) for column_name in batch: lowercase__ : Any = self._consolidate(batch[column_name] ) return batch
152
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
673
0
'''simple docstring''' from __future__ import annotations import time __lowercase : Dict = list[tuple[int, int]] __lowercase : List[str] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __lowercase : Union[str, Any] = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class __UpperCamelCase : def __init__( self , __a , __a , __a , __a , __a ): '''simple docstring''' __a : str = pos_x __a : Dict = pos_y __a : str = (pos_y, pos_x) __a : Optional[int] = goal_x __a : Union[str, Any] = goal_y __a : Union[str, Any] = parent class __UpperCamelCase : def __init__( self , __a , __a ): '''simple docstring''' __a : Any = Node(start[1] , start[0] , goal[1] , goal[0] , snake_case__ ) __a : Optional[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , snake_case__ ) __a : List[str] = [self.start] __a : Any = False def __UpperCAmelCase ( self ): '''simple docstring''' while self.node_queue: __a : str = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: __a : Optional[int] = True return self.retrace_path(snake_case__ ) __a : Tuple = self.get_successors(snake_case__ ) for node in successors: self.node_queue.append(snake_case__ ) if not self.reached: return [self.start.pos] return None def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : int = [] for action in delta: __a : Any = parent.pos_x + action[1] __a : Any = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(snake_case__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(snake_case__ , snake_case__ , self.target.pos_y , self.target.pos_x , snake_case__ ) ) return successors def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Union[str, Any] = node __a : Tuple = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __a : Optional[int] = current_node.parent path.reverse() return path class __UpperCamelCase : def __init__( self , __a , __a ): '''simple docstring''' __a : int = BreadthFirstSearch(snake_case__ , snake_case__ ) __a : Optional[int] = BreadthFirstSearch(snake_case__ , snake_case__ ) __a : Tuple = False def __UpperCAmelCase ( self ): '''simple docstring''' while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __a : Dict = self.fwd_bfs.node_queue.pop(0 ) __a : Optional[Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: __a : Optional[Any] = True return self.retrace_bidirectional_path( snake_case__ , snake_case__ ) __a : Any = current_bwd_node __a : Union[str, Any] = current_fwd_node __a : Dict = { self.fwd_bfs: self.fwd_bfs.get_successors(snake_case__ ), self.bwd_bfs: self.bwd_bfs.get_successors(snake_case__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(snake_case__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' __a : List[str] = self.fwd_bfs.retrace_path(snake_case__ ) __a : str = self.bwd_bfs.retrace_path(snake_case__ ) bwd_path.pop() bwd_path.reverse() __a : Tuple = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() __lowercase : str = (0, 0) __lowercase : Dict = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __lowercase : Optional[int] = time.time() __lowercase : str = BreadthFirstSearch(init, goal) __lowercase : Dict = bfs.search() __lowercase : List[Any] = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) __lowercase : Dict = time.time() __lowercase : List[Any] = BidirectionalBreadthFirstSearch(init, goal) __lowercase : Optional[Any] = bd_bfs.search() __lowercase : Any = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
476
"""simple docstring""" import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase_ ( a_ , unittest.TestCase ): _A : str = VideoToVideoSDPipeline _A : List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'} ) - {'image', 'width', 'height'} _A : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'} ) - {'image'} _A : int = PipelineTesterMixin.required_optional_params - {'latents'} _A : List[str] = False # No `output_type`. _A : Any = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'return_dict', 'callback', 'callback_steps', ] ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) UpperCAmelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=snake_case__ , set_alpha_to_one=snake_case__ , ) torch.manual_seed(0 ) UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="""gelu""" , projection_dim=5_12 , ) UpperCAmelCase = CLIPTextModel(snake_case__ ) UpperCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCAmelCase = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def UpperCamelCase_ ( self , snake_case__ , snake_case__=0 ) -> List[str]: """simple docstring""" UpperCAmelCase = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) if str(snake_case__ ).startswith("""mps""" ): UpperCAmelCase = torch.manual_seed(snake_case__ ) else: UpperCAmelCase = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) UpperCAmelCase = { """prompt""": """A painting of a squirrel eating a burger""", """video""": video, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = VideoToVideoSDPipeline(**snake_case__ ) UpperCAmelCase = sd_pipe.to(snake_case__ ) sd_pipe.set_progress_bar_config(disable=snake_case__ ) UpperCAmelCase = self.get_dummy_inputs(snake_case__ ) UpperCAmelCase = """np""" UpperCAmelCase = sd_pipe(**snake_case__ ).frames UpperCAmelCase = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) UpperCAmelCase = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=snake_case__ , expected_max_diff=5e-3 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return super().test_progress_bar() @slow @skip_mps class UpperCamelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = VideoToVideoSDPipeline.from_pretrained("""cerspense/zeroscope_v2_XL""" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames UpperCAmelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCAmelCase = torch.randn((1, 10, 3, 10_24, 5_76) , generator=snake_case__ ) UpperCAmelCase = video.to("""cuda""" ) UpperCAmelCase = """Spiderman is surfing""" UpperCAmelCase = pipe(snake_case__ , video=snake_case__ , generator=snake_case__ , num_inference_steps=3 , output_type="""pt""" ).frames UpperCAmelCase = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
673
0
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever A_ = logging.getLogger(__name__) class snake_case ( a_ ): '''simple docstring''' def __init__( self : Any , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Union[str, Any]=None ) -> Union[str, Any]: """simple docstring""" super().__init__( snake_case__ , question_encoder_tokenizer=snake_case__ , generator_tokenizer=snake_case__ , index=snake_case__ , init_retrieval=snake_case__ , ) SCREAMING_SNAKE_CASE_ = None def _lowercase ( self : Optional[int] , lowerCAmelCase_ : Optional[int] ) -> Tuple: """simple docstring""" logger.info('''initializing retrieval''' ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info('''dist initialized''' ) # needs to be set manually SCREAMING_SNAKE_CASE_ = self._infer_socket_ifname() # avoid clash with the NCCL port SCREAMING_SNAKE_CASE_ = str(distributed_port + 1 ) SCREAMING_SNAKE_CASE_ = dist.new_group(ranks=snake_case__ , backend='''gloo''' ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info('''dist not initialized / main''' ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def _lowercase ( self : int ) -> Optional[int]: """simple docstring""" return dist.get_rank(group=self.process_group ) == 0 def _lowercase ( self : Optional[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[Any]=torch.floataa ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ = torch.empty(snake_case__ , dtype=snake_case__ ) dist.scatter(snake_case__ , src=0 , scatter_list=snake_case__ , group=self.process_group ) return target_tensor def _lowercase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ = psutil.net_if_addrs() # a hacky way to deal with varying network interface names SCREAMING_SNAKE_CASE_ = next((addr for addr in addrs if addr.startswith('''e''' )) , snake_case__ ) return ifname def _lowercase ( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Tuple ) -> Tuple[np.ndarray, List[dict]]: """simple docstring""" if not dist.is_initialized(): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = self._main_retrieve(snake_case__ , snake_case__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(snake_case__ ) # distributed training SCREAMING_SNAKE_CASE_ = dist.get_world_size(group=self.process_group ) # gather logic SCREAMING_SNAKE_CASE_ = None if self._is_main(): SCREAMING_SNAKE_CASE_ = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(snake_case__ )] dist.gather(torch.tensor(snake_case__ ) , dst=0 , gather_list=snake_case__ , group=self.process_group ) # scatter logic SCREAMING_SNAKE_CASE_ = question_hidden_states.shape[0] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] if self._is_main(): assert len(snake_case__ ) == world_size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = self._main_retrieve(torch.cat(snake_case__ ).numpy() , snake_case__ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = torch.tensor(snake_case__ ), torch.tensor(snake_case__ ) SCREAMING_SNAKE_CASE_ = self._chunk_tensor(snake_case__ , snake_case__ ) SCREAMING_SNAKE_CASE_ = self._chunk_tensor(snake_case__ , snake_case__ ) SCREAMING_SNAKE_CASE_ = self._scattered(snake_case__ , [n_queries, n_docs] , target_type=torch.intaa ) SCREAMING_SNAKE_CASE_ = self._scattered(snake_case__ , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(snake_case__ )
393
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : int = logging.get_logger(__name__) lowerCAmelCase_ : Any = { '''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''', # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class UpperCamelCase_ ( a_ ): _A : int = 'wav2vec2' def __init__( self , snake_case__=32 , snake_case__=7_68 , snake_case__=12 , snake_case__=12 , snake_case__=30_72 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.02 , snake_case__=1e-5 , snake_case__="group" , snake_case__="gelu" , snake_case__=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , snake_case__=(5, 2, 2, 2, 2, 2, 2) , snake_case__=(10, 3, 3, 3, 3, 2, 2) , snake_case__=False , snake_case__=1_28 , snake_case__=16 , snake_case__=False , snake_case__=True , snake_case__=0.05 , snake_case__=10 , snake_case__=2 , snake_case__=0.0 , snake_case__=10 , snake_case__=0 , snake_case__=3_20 , snake_case__=2 , snake_case__=0.1 , snake_case__=1_00 , snake_case__=2_56 , snake_case__=2_56 , snake_case__=0.1 , snake_case__="sum" , snake_case__=False , snake_case__=False , snake_case__=2_56 , snake_case__=(5_12, 5_12, 5_12, 5_12, 15_00) , snake_case__=(5, 3, 3, 1, 1) , snake_case__=(1, 2, 3, 1, 1) , snake_case__=5_12 , snake_case__=0 , snake_case__=1 , snake_case__=2 , snake_case__=False , snake_case__=3 , snake_case__=2 , snake_case__=3 , snake_case__=None , snake_case__=None , **snake_case__ , ) -> Optional[Any]: """simple docstring""" super().__init__(**snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ ) UpperCAmelCase = hidden_size UpperCAmelCase = feat_extract_norm UpperCAmelCase = feat_extract_activation UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = conv_bias UpperCAmelCase = num_conv_pos_embeddings UpperCAmelCase = num_conv_pos_embedding_groups UpperCAmelCase = len(self.conv_dim ) UpperCAmelCase = num_hidden_layers UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = feat_proj_dropout UpperCAmelCase = final_dropout UpperCAmelCase = layerdrop UpperCAmelCase = layer_norm_eps UpperCAmelCase = initializer_range UpperCAmelCase = vocab_size UpperCAmelCase = do_stable_layer_norm UpperCAmelCase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCAmelCase = apply_spec_augment UpperCAmelCase = mask_time_prob UpperCAmelCase = mask_time_length UpperCAmelCase = mask_time_min_masks UpperCAmelCase = mask_feature_prob UpperCAmelCase = mask_feature_length UpperCAmelCase = mask_feature_min_masks # parameters for pretraining with codevector quantized representations UpperCAmelCase = num_codevectors_per_group UpperCAmelCase = num_codevector_groups UpperCAmelCase = contrastive_logits_temperature UpperCAmelCase = feat_quantizer_dropout UpperCAmelCase = num_negatives UpperCAmelCase = codevector_dim UpperCAmelCase = proj_codevector_dim UpperCAmelCase = diversity_loss_weight # ctc loss UpperCAmelCase = ctc_loss_reduction UpperCAmelCase = ctc_zero_infinity # adapter UpperCAmelCase = add_adapter UpperCAmelCase = adapter_kernel_size UpperCAmelCase = adapter_stride UpperCAmelCase = num_adapter_layers UpperCAmelCase = output_hidden_size or hidden_size UpperCAmelCase = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCAmelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = list(snake_case__ ) UpperCAmelCase = xvector_output_dim @property def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
673
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/config.json''', '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/config.json''', '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/config.json''', '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/config.json''', '''roberta-base-openai-detector''': '''https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json''', '''roberta-large-openai-detector''': '''https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json''', } class lowerCamelCase (a_ ): '''simple docstring''' _snake_case : Optional[int] = 'roberta' def __init__( self , _UpperCamelCase=5_0_2_6_5 , _UpperCamelCase=7_6_8 , _UpperCamelCase=1_2 , _UpperCamelCase=1_2 , _UpperCamelCase=3_0_7_2 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=5_1_2 , _UpperCamelCase=2 , _UpperCamelCase=0.02 , _UpperCamelCase=1E-12 , _UpperCamelCase=1 , _UpperCamelCase=0 , _UpperCamelCase=2 , _UpperCamelCase="absolute" , _UpperCamelCase=True , _UpperCamelCase=None , **_UpperCamelCase , ) -> List[str]: super().__init__(pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ ) UpperCAmelCase_ : str = vocab_size UpperCAmelCase_ : Any = hidden_size UpperCAmelCase_ : Optional[Any] = num_hidden_layers UpperCAmelCase_ : List[str] = num_attention_heads UpperCAmelCase_ : Tuple = hidden_act UpperCAmelCase_ : int = intermediate_size UpperCAmelCase_ : Tuple = hidden_dropout_prob UpperCAmelCase_ : Any = attention_probs_dropout_prob UpperCAmelCase_ : List[Any] = max_position_embeddings UpperCAmelCase_ : int = type_vocab_size UpperCAmelCase_ : Tuple = initializer_range UpperCAmelCase_ : Optional[int] = layer_norm_eps UpperCAmelCase_ : List[Any] = position_embedding_type UpperCAmelCase_ : List[Any] = use_cache UpperCAmelCase_ : Union[str, Any] = classifier_dropout class lowerCamelCase (a_ ): '''simple docstring''' @property def __UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": UpperCAmelCase_ : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCAmelCase_ : Tuple = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
406
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowerCAmelCase_ : Optional[Any] = NewType('''DataClass''', Any) lowerCAmelCase_ : Any = NewType('''DataClassType''', Any) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' if isinstance(lowerCAmelCase , lowerCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = {str(lowerCAmelCase ): choice for choice in choices} return lambda lowerCAmelCase : str_to_choice.get(lowerCAmelCase , lowerCAmelCase ) def _lowerCAmelCase ( *, lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase = dataclasses.MISSING , lowerCAmelCase = dataclasses.MISSING , lowerCAmelCase = None , **lowerCAmelCase , ): '''simple docstring''' if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls UpperCAmelCase = {} if aliases is not None: UpperCAmelCase = aliases if help is not None: UpperCAmelCase = help return dataclasses.field(metadata=lowerCAmelCase , default=lowerCAmelCase , default_factory=lowerCAmelCase , **lowerCAmelCase ) class UpperCamelCase_ ( a_ ): _A : Iterable[DataClassType] def __init__( self , snake_case__ , **snake_case__ ) -> List[str]: """simple docstring""" if "formatter_class" not in kwargs: UpperCAmelCase = ArgumentDefaultsHelpFormatter super().__init__(**snake_case__ ) if dataclasses.is_dataclass(snake_case__ ): UpperCAmelCase = [dataclass_types] UpperCAmelCase = list(snake_case__ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(snake_case__ ) @staticmethod def UpperCamelCase_ ( snake_case__ , snake_case__ ) -> str: """simple docstring""" UpperCAmelCase = f'''--{field.name}''' UpperCAmelCase = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , snake_case__ ): raise RuntimeError( """Unresolved type detected, which should have been done with the help of """ """`typing.get_type_hints` method by default""" ) UpperCAmelCase = kwargs.pop("""aliases""" , [] ) if isinstance(snake_case__ , snake_case__ ): UpperCAmelCase = [aliases] UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) if origin_type is Union or (hasattr(snake_case__ , """UnionType""" ) and isinstance(snake_case__ , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(snake_case__ ) not in field.type.__args__ ): raise ValueError( """Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because""" """ the argument parser only supports one type per argument.""" f''' Problem encountered in field \'{field.name}\'.''' ) if type(snake_case__ ) not in field.type.__args__: # filter `str` in Union UpperCAmelCase = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) UpperCAmelCase = ( field.type.__args__[0] if isinstance(snake_case__ , field.type.__args__[1] ) else field.type.__args__[1] ) UpperCAmelCase = getattr(field.type , """__origin__""" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) UpperCAmelCase = {} if origin_type is Literal or (isinstance(field.type , snake_case__ ) and issubclass(field.type , snake_case__ )): if origin_type is Literal: UpperCAmelCase = field.type.__args__ else: UpperCAmelCase = [x.value for x in field.type] UpperCAmelCase = make_choice_type_function(kwargs["""choices"""] ) if field.default is not dataclasses.MISSING: UpperCAmelCase = field.default else: UpperCAmelCase = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument UpperCAmelCase = copy(snake_case__ ) # Hack because type=bool in argparse does not behave as we want. UpperCAmelCase = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. UpperCAmelCase = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way UpperCAmelCase = default # This tells argparse we accept 0 or 1 value after --field_name UpperCAmelCase = """?""" # This is the value that will get picked if we do --field_name (without value) UpperCAmelCase = True elif isclass(snake_case__ ) and issubclass(snake_case__ , snake_case__ ): UpperCAmelCase = field.type.__args__[0] UpperCAmelCase = """+""" if field.default_factory is not dataclasses.MISSING: UpperCAmelCase = field.default_factory() elif field.default is dataclasses.MISSING: UpperCAmelCase = True else: UpperCAmelCase = field.type if field.default is not dataclasses.MISSING: UpperCAmelCase = field.default elif field.default_factory is not dataclasses.MISSING: UpperCAmelCase = field.default_factory() else: UpperCAmelCase = True parser.add_argument(snake_case__ , *snake_case__ , **snake_case__ ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): UpperCAmelCase = False parser.add_argument(f'''--no_{field.name}''' , action="""store_false""" , dest=field.name , **snake_case__ ) def UpperCamelCase_ ( self , snake_case__ ) -> Any: """simple docstring""" if hasattr(snake_case__ , """_argument_group_name""" ): UpperCAmelCase = self.add_argument_group(dtype._argument_group_name ) else: UpperCAmelCase = self try: UpperCAmelCase = get_type_hints(snake_case__ ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' """removing line of `from __future__ import annotations` which opts in Postponed """ """Evaluation of Annotations (PEP 563)""" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(snake_case__ ): UpperCAmelCase = """.""".join(map(snake_case__ , sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' """line of `from __future__ import annotations` which opts in union types as """ """`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To """ """support Python versions that lower than 3.10, you need to use """ """`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of """ """`X | None`.""" ) from ex raise for field in dataclasses.fields(snake_case__ ): if not field.init: continue UpperCAmelCase = type_hints[field.name] self._parse_dataclass_field(snake_case__ , snake_case__ ) def UpperCamelCase_ ( self , snake_case__=None , snake_case__=False , snake_case__=True , snake_case__=None , snake_case__=None , ) -> Tuple[DataClass, ...]: """simple docstring""" if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): UpperCAmelCase = [] if args_filename: args_files.append(Path(snake_case__ ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(""".args""" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values UpperCAmelCase = ArgumentParser() args_file_parser.add_argument(snake_case__ , type=snake_case__ , action="""append""" ) # Use only remaining args for further parsing (remove the args_file_flag) UpperCAmelCase , UpperCAmelCase = args_file_parser.parse_known_args(args=snake_case__ ) UpperCAmelCase = vars(snake_case__ ).get(args_file_flag.lstrip("""-""" ) , snake_case__ ) if cmd_args_file_paths: args_files.extend([Path(snake_case__ ) for p in cmd_args_file_paths] ) UpperCAmelCase = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last UpperCAmelCase = file_args + args if args is not None else file_args + sys.argv[1:] UpperCAmelCase , UpperCAmelCase = self.parse_known_args(args=snake_case__ ) UpperCAmelCase = [] for dtype in self.dataclass_types: UpperCAmelCase = {f.name for f in dataclasses.fields(snake_case__ ) if f.init} UpperCAmelCase = {k: v for k, v in vars(snake_case__ ).items() if k in keys} for k in keys: delattr(snake_case__ , snake_case__ ) UpperCAmelCase = dtype(**snake_case__ ) outputs.append(snake_case__ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(snake_case__ ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" UpperCAmelCase = set(args.keys() ) UpperCAmelCase = [] for dtype in self.dataclass_types: UpperCAmelCase = {f.name for f in dataclasses.fields(snake_case__ ) if f.init} UpperCAmelCase = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) UpperCAmelCase = dtype(**snake_case__ ) outputs.append(snake_case__ ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(snake_case__ )}''' ) return tuple(snake_case__ ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" with open(Path(snake_case__ ) , encoding="""utf-8""" ) as open_json_file: UpperCAmelCase = json.loads(open_json_file.read() ) UpperCAmelCase = self.parse_dict(snake_case__ , allow_extra_keys=snake_case__ ) return tuple(snake_case__ ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ = False ) -> Tuple[DataClass, ...]: """simple docstring""" UpperCAmelCase = self.parse_dict(yaml.safe_load(Path(snake_case__ ).read_text() ) , allow_extra_keys=snake_case__ ) return tuple(snake_case__ )
673
0
"""simple docstring""" import numpy class lowerCAmelCase__ : def __init__( self , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' A__ = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. A__ = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. A__ = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. A__ = numpy.random.rand(3 , 1 ) # Real output values provided. A__ = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. A__ = numpy.zeros(output_array.shape ) def lowercase_ ( self ): '''simple docstring''' A__ = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. A__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. A__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def lowercase_ ( self ): '''simple docstring''' A__ = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) A__ = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) A__ = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def lowercase_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' for iteration in range(1 , iterations + 1 ): A__ = self.feedforward() self.back_propagation() if give_loss: A__ = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f"""Iteration {iteration} Loss: {loss}""" ) def lowercase_ ( self , UpperCamelCase__ ): '''simple docstring''' A__ = input_arr A__ = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) A__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) A__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def __a ( A ) -> Dict: '''simple docstring''' return 1 / (1 + numpy.exp(-value )) def __a ( A ) -> List[str]: '''simple docstring''' return (value) * (1 - (value)) def __a ( ) -> int: '''simple docstring''' A__ = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. A__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. A__ = TwoHiddenLayerNeuralNetwork( input_array=A , output_array=A ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=A , iterations=10 , give_loss=A ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
337
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCAmelCase_ : List[str] = False class UpperCamelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self , snake_case__=32 ) -> Optional[Any]: """simple docstring""" set_seed(0 ) UpperCAmelCase = UNetaDModel(sample_size=snake_case__ , in_channels=3 , out_channels=3 ) UpperCAmelCase = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable UpperCAmelCase = DDPMScheduler( num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) UpperCAmelCase = DDIMScheduler( num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) UpperCAmelCase = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(snake_case__ ) for _ in range(4 )] UpperCAmelCase = [torch.randn((4, 3, 32, 32) ).to(snake_case__ ) for _ in range(4 )] UpperCAmelCase = [torch.randint(0 , 10_00 , (4,) ).long().to(snake_case__ ) for _ in range(4 )] # train with a DDPM scheduler UpperCAmelCase , UpperCAmelCase = self.get_model_optimizer(resolution=32 ) model.train().to(snake_case__ ) for i in range(4 ): optimizer.zero_grad() UpperCAmelCase = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) UpperCAmelCase = model(snake_case__ , timesteps[i] ).sample UpperCAmelCase = torch.nn.functional.mse_loss(snake_case__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM UpperCAmelCase , UpperCAmelCase = self.get_model_optimizer(resolution=32 ) model.train().to(snake_case__ ) for i in range(4 ): optimizer.zero_grad() UpperCAmelCase = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) UpperCAmelCase = model(snake_case__ , timesteps[i] ).sample UpperCAmelCase = torch.nn.functional.mse_loss(snake_case__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-5 ) )
673
0
'''simple docstring''' import re from filelock import FileLock try: import nltk __UpperCAmelCase =True except (ImportError, ModuleNotFoundError): __UpperCAmelCase =False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def __lowerCAmelCase ( UpperCamelCase__ ) -> Union[str, Any]: re.sub('''<n>''' , '''''' , UpperCamelCase__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase__ ) )
546
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class UpperCamelCase_ : def __init__( self , snake_case__=2 , snake_case__=3 , snake_case__=64 , snake_case__=None ) -> List[str]: """simple docstring""" UpperCAmelCase = np.random.default_rng(snake_case__ ) UpperCAmelCase = length UpperCAmelCase = rng.normal(size=(length,) ).astype(np.floataa ) UpperCAmelCase = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> int: """simple docstring""" return self.length def __getitem__( self , snake_case__ ) -> Tuple: """simple docstring""" return {"x": self.x[i], "y": self.y[i]} class UpperCamelCase_ ( torch.nn.Module ): def __init__( self , snake_case__=0 , snake_case__=0 , snake_case__=False ) -> List[str]: """simple docstring""" super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = True def UpperCamelCase_ ( self , snake_case__=None ) -> List[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCAmelCase = False return x * self.a[0] + self.b[0] class UpperCamelCase_ ( torch.nn.Module ): def __init__( self , snake_case__=0 , snake_case__=0 , snake_case__=False ) -> List[Any]: """simple docstring""" super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor(snake_case__ ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor(snake_case__ ).float() ) UpperCAmelCase = True def UpperCamelCase_ ( self , snake_case__=None ) -> Optional[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCAmelCase = False return x * self.a + self.b def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase = 16 ): '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer UpperCAmelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCAmelCase = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} UpperCAmelCase = load_dataset("""csv""" , data_files=lowerCAmelCase ) UpperCAmelCase = datasets["""train"""].unique("""label""" ) UpperCAmelCase = {v: i for i, v in enumerate(lowerCAmelCase )} def tokenize_function(lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase , max_length=lowerCAmelCase , padding="""max_length""" ) if "label" in examples: UpperCAmelCase = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase = datasets.map( lowerCAmelCase , batched=lowerCAmelCase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(lowerCAmelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCAmelCase = DataLoader(tokenized_datasets["""train"""] , shuffle=lowerCAmelCase , collate_fn=lowerCAmelCase , batch_size=2 ) UpperCAmelCase = DataLoader(tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase , collate_fn=lowerCAmelCase , batch_size=1 ) return train_dataloader, eval_dataloader
673
0
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path lowerCamelCase = [ {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.de'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.en'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.fr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.frr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.it'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.simple'''}, {'''dataset''': '''snli''', '''config_name''': '''plain_text'''}, {'''dataset''': '''eli5''', '''config_name''': '''LFQA_reddit'''}, {'''dataset''': '''wiki40b''', '''config_name''': '''en'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.compressed'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.no_index'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.multiset.no_index'''}, {'''dataset''': '''natural_questions''', '''config_name''': '''default'''}, ] def a_ ( SCREAMING_SNAKE_CASE__ : Optional[Any]=True ): '''simple docstring''' if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=a_ ) ) class A ( a_ ): UpperCamelCase__ : Tuple =None UpperCamelCase__ : List[Any] =None def lowerCamelCase ( self : List[Any] , lowercase_ : str , lowercase_ : Optional[int] ) -> Union[str, Any]: """simple docstring""" with TemporaryDirectory() as tmp_dir: _lowerCamelCase : Optional[Any] =dataset_module_factory(snake_case__ , cache_dir=snake_case__ ) _lowerCamelCase : Tuple =import_main_class(dataset_module.module_path , dataset=snake_case__ ) _lowerCamelCase : int =builder_cls( cache_dir=snake_case__ , config_name=snake_case__ , hash=dataset_module.hash , ) _lowerCamelCase : Optional[int] ='/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=snake_case__ ).replace(os.sep , '/' ), config.DATASET_INFO_FILENAME, ] ) _lowerCamelCase : Optional[Any] =cached_path(snake_case__ , cache_dir=snake_case__ ) self.assertTrue(os.path.exists(snake_case__ ) ) @pytest.mark.integration def a_ ( SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' _lowerCamelCase : Optional[int] =tmp_path_factory.mktemp('test_hf_gcp' ) / 'test_wikipedia_simple' _lowerCamelCase : Tuple =dataset_module_factory('wikipedia' , cache_dir=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[str] =import_main_class(dataset_module.module_path ) _lowerCamelCase : Optional[Any] =builder_cls( cache_dir=SCREAMING_SNAKE_CASE__ , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam _lowerCamelCase : Tuple =None builder_instance.download_and_prepare() _lowerCamelCase : List[str] =builder_instance.as_dataset() assert ds @pytest.mark.integration def a_ ( SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' _lowerCamelCase : Any =dataset_module_factory('wikipedia' , cache_dir=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Optional[int] =import_main_class(dataset_module.module_path , dataset=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Union[str, Any] =builder_cls( cache_dir=SCREAMING_SNAKE_CASE__ , config_name='20220301.frr' , hash=dataset_module.hash , ) _lowerCamelCase : str =builder_instance.as_streaming_dataset() assert ds assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert "train" in ds assert isinstance(ds['train'] , SCREAMING_SNAKE_CASE__ ) assert next(iter(ds['train'] ) )
464
"""simple docstring""" import flax.linen as nn import jax import jax.numpy as jnp class UpperCamelCase_ ( nn.Module ): _A : int _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , snake_case__ ) -> Tuple: """simple docstring""" UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = hidden_states.shape UpperCAmelCase = jax.image.resize( snake_case__ , shape=(batch, height * 2, width * 2, channels) , method="""nearest""" , ) UpperCAmelCase = self.conv(snake_case__ ) return hidden_states class UpperCamelCase_ ( nn.Module ): _A : int _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , snake_case__ ) -> Any: """simple docstring""" UpperCAmelCase = self.conv(snake_case__ ) return hidden_states class UpperCamelCase_ ( nn.Module ): _A : int _A : int = None _A : float = 0.0 _A : bool = None _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.in_channels if self.out_channels is None else self.out_channels UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = nn.Dense(snake_case__ , dtype=self.dtype ) UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCAmelCase = nn.Dropout(self.dropout_prob ) UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCAmelCase = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut UpperCAmelCase = None if use_nin_shortcut: UpperCAmelCase = nn.Conv( snake_case__ , kernel_size=(1, 1) , strides=(1, 1) , padding="""VALID""" , dtype=self.dtype , ) def __call__( self , snake_case__ , snake_case__ , snake_case__=True ) -> List[Any]: """simple docstring""" UpperCAmelCase = hidden_states UpperCAmelCase = self.norma(snake_case__ ) UpperCAmelCase = nn.swish(snake_case__ ) UpperCAmelCase = self.conva(snake_case__ ) UpperCAmelCase = self.time_emb_proj(nn.swish(snake_case__ ) ) UpperCAmelCase = jnp.expand_dims(jnp.expand_dims(snake_case__ , 1 ) , 1 ) UpperCAmelCase = hidden_states + temb UpperCAmelCase = self.norma(snake_case__ ) UpperCAmelCase = nn.swish(snake_case__ ) UpperCAmelCase = self.dropout(snake_case__ , snake_case__ ) UpperCAmelCase = self.conva(snake_case__ ) if self.conv_shortcut is not None: UpperCAmelCase = self.conv_shortcut(snake_case__ ) return hidden_states + residual
673
0
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow UpperCAmelCase : List[str] = False class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def _UpperCAmelCase ( self : Optional[Any] , lowerCAmelCase_ : List[str]=3_2): """simple docstring""" set_seed(0) lowercase_ = UNetaDModel(sample_size=snake_case__ , in_channels=3 , out_channels=3) lowercase_ = torch.optim.SGD(model.parameters() , lr=0.0_001) return model, optimizer @slow def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowercase_ = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) lowercase_ = DDIMScheduler( num_train_timesteps=1_0_0_0 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=snake_case__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0) lowercase_ = [torch.randn((4, 3, 3_2, 3_2)).clip(-1 , 1).to(snake_case__) for _ in range(4)] lowercase_ = [torch.randn((4, 3, 3_2, 3_2)).to(snake_case__) for _ in range(4)] lowercase_ = [torch.randint(0 , 1_0_0_0 , (4,)).long().to(snake_case__) for _ in range(4)] # train with a DDPM scheduler lowercase_ , lowercase_ = self.get_model_optimizer(resolution=3_2) model.train().to(snake_case__) for i in range(4): optimizer.zero_grad() lowercase_ = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i]) lowercase_ = model(snake_case__ , timesteps[i]).sample lowercase_ = torch.nn.functional.mse_loss(snake_case__ , noise[i]) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowercase_ , lowercase_ = self.get_model_optimizer(resolution=3_2) model.train().to(snake_case__) for i in range(4): optimizer.zero_grad() lowercase_ = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i]) lowercase_ = model(snake_case__ , timesteps[i]).sample lowercase_ = torch.nn.functional.mse_loss(snake_case__ , noise[i]) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1E-5)) self.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1E-5))
567
"""simple docstring""" from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=13 , snake_case__=30 , snake_case__=2 , snake_case__=3 , snake_case__=True , snake_case__=True , snake_case__=32 , snake_case__=2 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=10 , snake_case__=0.02 , snake_case__=3 , snake_case__=None , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase = (image_size // patch_size) ** 2 UpperCAmelCase = num_patches + 1 def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" return ViTConfig( 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=snake_case__ , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = TFViTModel(config=snake_case__ ) UpperCAmelCase = model(snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase = self.image_size // 2 UpperCAmelCase = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) UpperCAmelCase = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.type_sequence_label_size UpperCAmelCase = TFViTForImageClassification(snake_case__ ) UpperCAmelCase = model(snake_case__ , labels=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase = self.image_size // 2 UpperCAmelCase = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase = model(snake_case__ , interpolate_pos_encoding=snake_case__ , training=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase = 1 UpperCAmelCase = TFViTForImageClassification(snake_case__ ) UpperCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase = model(snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Optional[int] = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () _A : Optional[Any] = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) _A : Optional[int] = False _A : Any = False _A : List[str] = False def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = TFViTModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=37 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , tf.keras.layers.Layer ) ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) UpperCAmelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case__ ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) @slow def UpperCamelCase_ ( self ) -> str: """simple docstring""" UpperCAmelCase = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(snake_case__ ) def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCamelCase_ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=snake_case__ , return_tensors="""tf""" ) # forward pass UpperCAmelCase = model(**snake_case__ ) # verify the logits UpperCAmelCase = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , snake_case__ ) UpperCAmelCase = tf.constant([-0.2_744, 0.8_215, -0.0_836] ) tf.debugging.assert_near(outputs.logits[0, :3] , snake_case__ , atol=1e-4 )
673
0
"""simple docstring""" import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() _lowerCamelCase = logging.get_logger('''transformers.models.speecht5''') _lowerCamelCase = { '''speech_encoder_prenet.layer_norm''': '''speecht5.encoder.prenet.feature_projection.layer_norm''', '''speech_encoder_prenet.post_extract_proj''': '''speecht5.encoder.prenet.feature_projection.projection''', '''speech_encoder_prenet.pos_conv.0''': '''speecht5.encoder.prenet.pos_conv_embed.conv''', '''speech_encoder_prenet.mask_emb''': '''speecht5.encoder.prenet.masked_spec_embed''', } _lowerCamelCase = { '''text_encoder_prenet.encoder_prenet.0''': '''speecht5.encoder.prenet.embed_tokens''', '''text_encoder_prenet.encoder_prenet.1.alpha''': '''speecht5.encoder.prenet.encode_positions.alpha''', } _lowerCamelCase = { '''speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0''': '''speecht5.decoder.prenet.layers.0''', '''speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0''': '''speecht5.decoder.prenet.layers.1''', '''speech_decoder_prenet.decoder_prenet.0.1''': '''speecht5.decoder.prenet.final_layer''', '''speech_decoder_prenet.decoder_prenet.1.alpha''': '''speecht5.decoder.prenet.encode_positions.alpha''', '''speech_decoder_prenet.spkembs_layer.0''': '''speecht5.decoder.prenet.speaker_embeds_layer''', } _lowerCamelCase = { '''speech_decoder_postnet.feat_out''': '''speech_decoder_postnet.feat_out''', '''speech_decoder_postnet.prob_out''': '''speech_decoder_postnet.prob_out''', '''speech_decoder_postnet.postnet.postnet.0.0''': '''speech_decoder_postnet.layers.0.conv''', '''speech_decoder_postnet.postnet.postnet.0.1''': '''speech_decoder_postnet.layers.0.batch_norm''', '''speech_decoder_postnet.postnet.postnet.1.0''': '''speech_decoder_postnet.layers.1.conv''', '''speech_decoder_postnet.postnet.postnet.1.1''': '''speech_decoder_postnet.layers.1.batch_norm''', '''speech_decoder_postnet.postnet.postnet.2.0''': '''speech_decoder_postnet.layers.2.conv''', '''speech_decoder_postnet.postnet.postnet.2.1''': '''speech_decoder_postnet.layers.2.batch_norm''', '''speech_decoder_postnet.postnet.postnet.3.0''': '''speech_decoder_postnet.layers.3.conv''', '''speech_decoder_postnet.postnet.postnet.3.1''': '''speech_decoder_postnet.layers.3.batch_norm''', '''speech_decoder_postnet.postnet.postnet.4.0''': '''speech_decoder_postnet.layers.4.conv''', '''speech_decoder_postnet.postnet.postnet.4.1''': '''speech_decoder_postnet.layers.4.batch_norm''', } _lowerCamelCase = { '''text_decoder_prenet.embed_tokens''': '''speecht5.decoder.prenet.embed_tokens''', } _lowerCamelCase = { '''text_decoder_postnet.output_projection''': '''text_decoder_postnet.lm_head''', } _lowerCamelCase = { '''encoder.layers.*.self_attn.k_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj''', '''encoder.layers.*.self_attn.v_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj''', '''encoder.layers.*.self_attn.q_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj''', '''encoder.layers.*.self_attn.out_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj''', '''encoder.layers.*.self_attn_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.layer_norm''', '''encoder.layers.*.fc1''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense''', '''encoder.layers.*.fc2''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense''', '''encoder.layers.*.final_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''speecht5.encoder.wrapped_encoder.layer_norm''', '''encoder.pos_emb.pe_k''': '''speecht5.encoder.wrapped_encoder.embed_positions.pe_k''', } _lowerCamelCase = { '''decoder.layers.*.self_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj''', '''decoder.layers.*.self_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj''', '''decoder.layers.*.self_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj''', '''decoder.layers.*.self_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj''', '''decoder.layers.*.self_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm''', '''decoder.layers.*.encoder_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj''', '''decoder.layers.*.encoder_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj''', '''decoder.layers.*.encoder_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj''', '''decoder.layers.*.encoder_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj''', '''decoder.layers.*.encoder_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm''', '''decoder.layers.*.fc1''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense''', '''decoder.layers.*.fc2''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense''', '''decoder.layers.*.final_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm''', } _lowerCamelCase = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } _lowerCamelCase = { **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _lowerCamelCase = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _lowerCamelCase = [] _lowerCamelCase = [ '''encoder.version''', '''encoder.layers.*.norm_k.weight''', '''encoder.layers.*.norm_k.bias''', '''decoder.version''', '''decoder.layers.*.norm_k.weight''', '''decoder.layers.*.norm_k.bias''', '''decoder.pos_emb.pe_k''', '''speech_encoder_prenet.embed_positions._float_tensor''', '''text_decoder_prenet.embed_positions._float_tensor''', ] _lowerCamelCase = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''speech_decoder_prenet.*''', '''speech_decoder_postnet.*''', ] _lowerCamelCase = IGNORE_KEYS + [ '''encoder.proj''', '''speech_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] _lowerCamelCase = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : str , lowercase_ : Any , lowercase_ : str , lowercase_ : Tuple ): '''simple docstring''' for attribute in key.split('''.''' ): __SCREAMING_SNAKE_CASE : Dict = getattr(lowercase_ , lowercase_ ) if weight_type is not None: __SCREAMING_SNAKE_CASE : str = getattr(lowercase_ , lowercase_ ).shape else: __SCREAMING_SNAKE_CASE : List[str] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": __SCREAMING_SNAKE_CASE : str = value elif weight_type == "weight_g": __SCREAMING_SNAKE_CASE : int = value elif weight_type == "weight_v": __SCREAMING_SNAKE_CASE : Dict = value elif weight_type == "bias": __SCREAMING_SNAKE_CASE : List[Any] = value elif weight_type == "running_mean": __SCREAMING_SNAKE_CASE : List[Any] = value elif weight_type == "running_var": __SCREAMING_SNAKE_CASE : int = value elif weight_type == "num_batches_tracked": __SCREAMING_SNAKE_CASE : Optional[int] = value else: __SCREAMING_SNAKE_CASE : List[Any] = value logger.info(F'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Dict , lowercase_ : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [] if task == "s2t": __SCREAMING_SNAKE_CASE : int = hf_model.speechta.encoder.prenet.feature_encoder __SCREAMING_SNAKE_CASE : List[str] = MAPPING_S2T __SCREAMING_SNAKE_CASE : Optional[Any] = IGNORE_KEYS_S2T elif task == "t2s": __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[int] = MAPPING_T2S __SCREAMING_SNAKE_CASE : Dict = IGNORE_KEYS_T2S elif task == "s2s": __SCREAMING_SNAKE_CASE : Dict = hf_model.speechta.encoder.prenet.feature_encoder __SCREAMING_SNAKE_CASE : Any = MAPPING_S2S __SCREAMING_SNAKE_CASE : List[Any] = IGNORE_KEYS_S2S else: raise ValueError(F'''Unsupported task: {task}''' ) for name, value in fairseq_dict.items(): if should_ignore(lowercase_ , lowercase_ ): logger.info(F'''{name} was ignored''' ) continue __SCREAMING_SNAKE_CASE : Optional[Any] = False if "conv_layers" in name: load_conv_layer( lowercase_ , lowercase_ , lowercase_ , lowercase_ , hf_model.config.feat_extract_norm == '''group''' , ) __SCREAMING_SNAKE_CASE : Tuple = True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = key.split('''.*.''' ) if prefix in name and suffix in name: __SCREAMING_SNAKE_CASE : str = suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: __SCREAMING_SNAKE_CASE : Any = True if "*" in mapped_key: __SCREAMING_SNAKE_CASE : Tuple = name.split(lowercase_ )[0].split('''.''' )[-2] __SCREAMING_SNAKE_CASE : int = mapped_key.replace('''*''' , lowercase_ ) if "weight_g" in name: __SCREAMING_SNAKE_CASE : int = '''weight_g''' elif "weight_v" in name: __SCREAMING_SNAKE_CASE : str = '''weight_v''' elif "bias" in name: __SCREAMING_SNAKE_CASE : Any = '''bias''' elif "weight" in name: __SCREAMING_SNAKE_CASE : Optional[Any] = '''weight''' elif "running_mean" in name: __SCREAMING_SNAKE_CASE : int = '''running_mean''' elif "running_var" in name: __SCREAMING_SNAKE_CASE : List[Any] = '''running_var''' elif "num_batches_tracked" in name: __SCREAMING_SNAKE_CASE : int = '''num_batches_tracked''' else: __SCREAMING_SNAKE_CASE : List[str] = None set_recursively(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) continue if not is_used: unused_weights.append(lowercase_ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = full_name.split('''conv_layers.''' )[-1] __SCREAMING_SNAKE_CASE : int = name.split('''.''' ) __SCREAMING_SNAKE_CASE : Any = int(items[0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : Any = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : Dict = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : List[str] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : str = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase_ ) @torch.no_grad() def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Any , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple=None , lowercase_ : str=None , ): '''simple docstring''' if config_path is not None: __SCREAMING_SNAKE_CASE : Dict = SpeechTaConfig.from_pretrained(lowercase_ ) else: __SCREAMING_SNAKE_CASE : List[str] = SpeechTaConfig() if task == "s2t": __SCREAMING_SNAKE_CASE : Optional[int] = config.max_text_positions __SCREAMING_SNAKE_CASE : int = SpeechTaForSpeechToText(lowercase_ ) elif task == "t2s": __SCREAMING_SNAKE_CASE : Optional[int] = 1876 __SCREAMING_SNAKE_CASE : Optional[int] = 600 __SCREAMING_SNAKE_CASE : List[str] = config.max_speech_positions __SCREAMING_SNAKE_CASE : int = SpeechTaForTextToSpeech(lowercase_ ) elif task == "s2s": __SCREAMING_SNAKE_CASE : Optional[Any] = 1876 __SCREAMING_SNAKE_CASE : Any = config.max_speech_positions __SCREAMING_SNAKE_CASE : Optional[int] = SpeechTaForSpeechToSpeech(lowercase_ ) else: raise ValueError(F'''Unknown task name: {task}''' ) if vocab_path: __SCREAMING_SNAKE_CASE : Any = SpeechTaTokenizer(lowercase_ , model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it __SCREAMING_SNAKE_CASE : List[Any] = AddedToken('''<mask>''' , lstrip=lowercase_ , rstrip=lowercase_ ) __SCREAMING_SNAKE_CASE : int = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) __SCREAMING_SNAKE_CASE : Optional[Any] = SpeechTaFeatureExtractor() __SCREAMING_SNAKE_CASE : Dict = SpeechTaProcessor(tokenizer=lowercase_ , feature_extractor=lowercase_ ) processor.save_pretrained(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = torch.load(lowercase_ ) recursively_load_weights(fairseq_checkpoint['''model'''] , lowercase_ , lowercase_ ) model.save_pretrained(lowercase_ ) if repo_id: print('''Pushing to the hub...''' ) processor.push_to_hub(lowercase_ ) model.push_to_hub(lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '''--task''', default='''s2t''', type=str, help='''Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--vocab_path''', default=None, type=str, help='''Path to SentencePiece model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) _lowerCamelCase = parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import numpy as np def lowerCAmelCase_ ( lowercase_ : np.ndarray , lowercase_ : np.ndarray , lowercase_ : float = 1E-1_2 , lowercase_ : int = 100 , ): '''simple docstring''' assert np.shape(lowercase_ )[0] == np.shape(lowercase_ )[1] # Ensure proper dimensionality. assert np.shape(lowercase_ )[0] == np.shape(lowercase_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(lowercase_ ) == np.iscomplexobj(lowercase_ ) __SCREAMING_SNAKE_CASE : Any = np.iscomplexobj(lowercase_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(lowercase_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE : Optional[Any] = False __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 __SCREAMING_SNAKE_CASE : Any = 0 __SCREAMING_SNAKE_CASE : Any = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE : int = np.dot(lowercase_ , lowercase_ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE : int = w / np.linalg.norm(lowercase_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE : Optional[Any] = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE : Optional[int] = np.dot(lowercase_ , np.dot(lowercase_ , lowercase_ ) ) # Check convergence. __SCREAMING_SNAKE_CASE : int = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE : Optional[int] = True __SCREAMING_SNAKE_CASE : str = lambda_ if is_complex: __SCREAMING_SNAKE_CASE : Optional[int] = np.real(lambda_ ) return lambda_, vector def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE : Dict = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE : List[str] = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE : int = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE : int = real_input_matrix __SCREAMING_SNAKE_CASE : str = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE : Dict = complex_input_matrix __SCREAMING_SNAKE_CASE : Optional[int] = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = power_iteration(lowercase_ , lowercase_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = np.linalg.eigh(lowercase_ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE : int = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE : Dict = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(lowercase_ ) - np.abs(lowercase_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '''▁''' _lowerCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model'''} _lowerCamelCase = { '''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''' ), } } _lowerCamelCase = { '''facebook/mbart-large-50-one-to-many-mmt''': 10_24, } # fmt: off _lowerCamelCase = ['''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 snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] lowerCamelCase__ = [] lowerCamelCase__ = [] def __init__( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=None , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :int="</s>" , _lowerCamelCase :Optional[Any]="</s>" , _lowerCamelCase :Union[str, Any]="<s>" , _lowerCamelCase :int="<unk>" , _lowerCamelCase :List[str]="<pad>" , _lowerCamelCase :int="<mask>" , _lowerCamelCase :Optional[Dict[str, Any]] = None , **_lowerCamelCase :List[Any] , ): # Mask token behave like a normal word, i.e. include the space before it __SCREAMING_SNAKE_CASE : Any = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token __SCREAMING_SNAKE_CASE : List[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=_lowerCamelCase , tgt_lang=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : 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 : List[Any] = {'''<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 : Optional[int] = len(self.sp_model ) __SCREAMING_SNAKE_CASE : List[str] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_lowerCamelCase ) } __SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in self.lang_code_to_id.items()} __SCREAMING_SNAKE_CASE : Union[str, Any] = 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 : Optional[int] = {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 : Any = self.lang_code_to_id[self._src_lang] __SCREAMING_SNAKE_CASE : Tuple = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def SCREAMING_SNAKE_CASE_ ( self :Any ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self._src_lang @src_lang.setter def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : List[str] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self :List[Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : Dict = None return state def __setstate__( self :Tuple , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : List[Any] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :str ): return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :str ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __SCREAMING_SNAKE_CASE : int = self.sp_model.PieceToId(_lowerCamelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :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 SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Tuple = [] __SCREAMING_SNAKE_CASE : Any = '''''' __SCREAMING_SNAKE_CASE : Tuple = 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(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : Union[str, Any] = True __SCREAMING_SNAKE_CASE : Optional[int] = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : Tuple = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = [1] * len(self.prefix_tokens ) __SCREAMING_SNAKE_CASE : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_lowerCamelCase )) + suffix_ones return prefix_ones + ([0] * len(_lowerCamelCase )) + ([0] * len(_lowerCamelCase )) + suffix_ones def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :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 SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] , _lowerCamelCase :Optional[str] , **_lowerCamelCase :List[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 : Optional[int] = src_lang __SCREAMING_SNAKE_CASE : Union[str, Any] = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = tgt_lang_id return inputs def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :List[str] , _lowerCamelCase :str = "en_XX" , _lowerCamelCase :Optional[List[str]] = None , _lowerCamelCase :str = "ro_RO" , **_lowerCamelCase :Optional[int] , ): __SCREAMING_SNAKE_CASE : Optional[Any] = src_lang __SCREAMING_SNAKE_CASE : int = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.set_src_lang_special_tokens(self.src_lang ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Dict = self.lang_code_to_id[src_lang] __SCREAMING_SNAKE_CASE : List[Any] = [self.cur_lang_code_id] __SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : str = self.lang_code_to_id[tgt_lang] __SCREAMING_SNAKE_CASE : Dict = [self.cur_lang_code_id] __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id]
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer 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.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer 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.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node _lowerCamelCase = 4 _lowerCamelCase = 3 class snake_case ( __UpperCAmelCase ): pass def lowerCAmelCase_ ( lowercase_ : List[str] ): '''simple docstring''' for shard in shards: for i in range(lowercase_ ): yield {"i": i, "shard": shard} def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = int(os.environ['''RANK'''] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(os.environ['''WORLD_SIZE'''] ) __SCREAMING_SNAKE_CASE : List[str] = ArgumentParser() parser.add_argument('''--streaming''' , type=lowercase_ ) parser.add_argument('''--local_rank''' , type=lowercase_ ) parser.add_argument('''--num_workers''' , type=lowercase_ , default=0 ) __SCREAMING_SNAKE_CASE : Tuple = parser.parse_args() __SCREAMING_SNAKE_CASE : int = args.streaming __SCREAMING_SNAKE_CASE : Any = args.num_workers __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''shards''': [F'''shard_{shard_idx}''' for shard_idx in range(lowercase_ )]} __SCREAMING_SNAKE_CASE : Optional[int] = IterableDataset.from_generator(lowercase_ , gen_kwargs=lowercase_ ) if not streaming: __SCREAMING_SNAKE_CASE : List[str] = Dataset.from_list(list(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = split_dataset_by_node(lowercase_ , rank=lowercase_ , world_size=lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.utils.data.DataLoader(lowercase_ , num_workers=lowercase_ ) __SCREAMING_SNAKE_CASE : Any = NUM_SHARDS * NUM_ITEMS_PER_SHARD __SCREAMING_SNAKE_CASE : int = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) __SCREAMING_SNAKE_CASE : Dict = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'''local_size {local_size} != expected_local_size {expected_local_size}''' ) if __name__ == "__main__": main()
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" _lowerCamelCase = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] _lowerCamelCase = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] _lowerCamelCase = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int , lowercase_ : int ): '''simple docstring''' assert len(str(lowercase_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __SCREAMING_SNAKE_CASE : List[str] = year // 100 __SCREAMING_SNAKE_CASE : str = (5 * (century % 4) + 2) % 7 __SCREAMING_SNAKE_CASE : Dict = year % 100 __SCREAMING_SNAKE_CASE : List[Any] = centurian % 12 __SCREAMING_SNAKE_CASE : Union[str, Any] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __SCREAMING_SNAKE_CASE : List[Any] = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" import copy import os import cva import numpy as np from matplotlib import pyplot as plt class snake_case : def __init__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = '''''' __SCREAMING_SNAKE_CASE : Tuple = '''''' __SCREAMING_SNAKE_CASE : Union[str, Any] = [] __SCREAMING_SNAKE_CASE : Any = 0 __SCREAMING_SNAKE_CASE : Any = 2_5_6 __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : Dict = 0 def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : str = cva.imread(_lowerCamelCase , 0 ) __SCREAMING_SNAKE_CASE : List[str] = copy.deepcopy(self.img ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = plt.hist(self.img.ravel() , 2_5_6 , [0, 2_5_6] , label='''x''' ) __SCREAMING_SNAKE_CASE : Optional[int] = np.sum(_lowerCamelCase ) for i in range(len(_lowerCamelCase ) ): __SCREAMING_SNAKE_CASE : List[str] = x[i] / self.k self.sk += prk __SCREAMING_SNAKE_CASE : str = (self.L - 1) * self.sk if self.rem != 0: __SCREAMING_SNAKE_CASE : Optional[int] = int(last % last ) __SCREAMING_SNAKE_CASE : int = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = int(np.ma.count(self.img ) / self.img[1].size ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): __SCREAMING_SNAKE_CASE : Optional[int] = self.img[j][i] if num != self.last_list[num]: __SCREAMING_SNAKE_CASE : Dict = self.last_list[num] cva.imwrite('''output_data/output.jpg''' , self.img ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): plt.hist(self.img.ravel() , 2_5_6 , [0, 2_5_6] ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): cva.imshow('''Output-Image''' , self.img ) cva.imshow('''Input-Image''' , self.original_image ) cva.waitKey(5_0_0_0 ) cva.destroyAllWindows() if __name__ == "__main__": _lowerCamelCase = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') _lowerCamelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
674
"""simple docstring""" 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 _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = 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=3_84, 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=1_28, 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''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = 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) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 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 _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 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) _lowerCamelCase = 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) _lowerCamelCase = 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_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[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 : Tuple = 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 : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (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. _lowerCamelCase = 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. _lowerCamelCase = 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. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = 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}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [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 : Optional[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 : Optional[int] = 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 : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 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 : str = 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 : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = 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''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = 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 : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = 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_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = 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}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = 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 * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self :Dict , _lowerCamelCase :List[Any] , _lowerCamelCase :Union[str, Any]=1_3 , _lowerCamelCase :List[Any]=3_2 , _lowerCamelCase :Tuple=3 , _lowerCamelCase :int=4 , _lowerCamelCase :List[Any]=[1_0, 2_0, 3_0, 4_0] , _lowerCamelCase :Optional[int]=[2, 2, 3, 2] , _lowerCamelCase :Dict=True , _lowerCamelCase :Tuple=True , _lowerCamelCase :int=3_7 , _lowerCamelCase :Optional[Any]="gelu" , _lowerCamelCase :Any=1_0 , _lowerCamelCase :Optional[Any]=0.0_2 , _lowerCamelCase :str=["stage2", "stage3", "stage4"] , _lowerCamelCase :List[Any]=[2, 3, 4] , _lowerCamelCase :int=None , ): __SCREAMING_SNAKE_CASE : Optional[int] = parent __SCREAMING_SNAKE_CASE : str = batch_size __SCREAMING_SNAKE_CASE : int = image_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : Tuple = num_stages __SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_sizes __SCREAMING_SNAKE_CASE : Any = depths __SCREAMING_SNAKE_CASE : int = is_training __SCREAMING_SNAKE_CASE : str = use_labels __SCREAMING_SNAKE_CASE : int = intermediate_size __SCREAMING_SNAKE_CASE : Dict = hidden_act __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Tuple = initializer_range __SCREAMING_SNAKE_CASE : Any = out_features __SCREAMING_SNAKE_CASE : int = out_indices __SCREAMING_SNAKE_CASE : Dict = scope def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_labels: __SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.num_labels ) __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self :int ): return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :int , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = ConvNextVaModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :str , _lowerCamelCase :List[str] , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[Any] = ConvNextVaForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Any , _lowerCamelCase :Any , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[int] = ConvNextVaBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __SCREAMING_SNAKE_CASE : str = None __SCREAMING_SNAKE_CASE : List[Any] = ConvNextVaBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = config_and_inputs __SCREAMING_SNAKE_CASE : List[str] = {'''pixel_values''': pixel_values} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = config_and_inputs __SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': pixel_values, '''labels''': labels} return config, inputs_dict @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCamelCase__ = ( {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = ConvNextVaModelTester(self ) __SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE_ ( 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 SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :str ): pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Any ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_with_labels() __SCREAMING_SNAKE_CASE : List[Any] = True if model_class.__name__ in [ *get_values(_lowerCamelCase ), *get_values(_lowerCamelCase ), ]: continue __SCREAMING_SNAKE_CASE : List[str] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : List[str] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_with_labels() __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : Union[str, Any] = True if ( model_class.__name__ in [*get_values(_lowerCamelCase ), *get_values(_lowerCamelCase )] or not model_class.supports_gradient_checkpointing ): continue __SCREAMING_SNAKE_CASE : str = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.gradient_checkpointing_enable() model.train() __SCREAMING_SNAKE_CASE : int = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = model(**_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = 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 : str = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): def check_hidden_states_output(_lowerCamelCase :Tuple , _lowerCamelCase :int , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Optional[Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Optional[Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE : Optional[Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = ConvNextVaModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : Any = prepare_img() __SCREAMING_SNAKE_CASE : List[str] = preprocessor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE : Dict = model(**_lowerCamelCase ) # verify the logits __SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class snake_case ( unittest.TestCase ): lowerCamelCase__ = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[str] = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) __SCREAMING_SNAKE_CASE : List[Any] = VideoClassificationPipeline(model=_lowerCamelCase , image_processor=_lowerCamelCase , top_k=2 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Tuple , _lowerCamelCase :Dict ): for example in examples: __SCREAMING_SNAKE_CASE : int = video_classifier(_lowerCamelCase ) self.assertEqual( _lowerCamelCase , [ {'''score''': ANY(_lowerCamelCase ), '''label''': ANY(_lowerCamelCase )}, {'''score''': ANY(_lowerCamelCase ), '''label''': ANY(_lowerCamelCase )}, ] , ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' __SCREAMING_SNAKE_CASE : Tuple = VideoMAEFeatureExtractor( size={'''shortest_edge''': 1_0} , crop_size={'''height''': 1_0, '''width''': 1_0} ) __SCREAMING_SNAKE_CASE : Optional[Any] = pipeline( '''video-classification''' , model=_lowerCamelCase , feature_extractor=_lowerCamelCase , frame_sampling_rate=4 ) __SCREAMING_SNAKE_CASE : int = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) __SCREAMING_SNAKE_CASE : List[Any] = video_classifier(_lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(_lowerCamelCase , decimals=4 ) , [{'''score''': 0.5_1_9_9, '''label''': '''LABEL_0'''}, {'''score''': 0.4_8_0_1, '''label''': '''LABEL_1'''}] , ) __SCREAMING_SNAKE_CASE : List[str] = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_lowerCamelCase , decimals=4 ) , [ [{'''score''': 0.5_1_9_9, '''label''': '''LABEL_0'''}, {'''score''': 0.4_8_0_1, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_1_9_9, '''label''': '''LABEL_0'''}, {'''score''': 0.4_8_0_1, '''label''': '''LABEL_1'''}], ] , ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :str ): pass
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = 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(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : list , lowercase_ : list ): '''simple docstring''' _validate_point(lowercase_ ) _validate_point(lowercase_ ) if len(lowercase_ ) != len(lowercase_ ): raise ValueError('''Both points must be in the same n-dimensional space''' ) return float(sum(abs(a - b ) for a, b in zip(lowercase_ , lowercase_ ) ) ) def lowerCAmelCase_ ( lowercase_ : list[float] ): '''simple docstring''' if point: if isinstance(lowercase_ , lowercase_ ): for item in point: if not isinstance(lowercase_ , (int, float) ): __SCREAMING_SNAKE_CASE : Dict = ( '''Expected a list of numbers as input, found ''' F'''{type(lowercase_ ).__name__}''' ) raise TypeError(lowercase_ ) else: __SCREAMING_SNAKE_CASE : int = F'''Expected a list of numbers as input, found {type(lowercase_ ).__name__}''' raise TypeError(lowercase_ ) else: raise ValueError('''Missing an input''' ) def lowerCAmelCase_ ( lowercase_ : list , lowercase_ : list ): '''simple docstring''' _validate_point(lowercase_ ) _validate_point(lowercase_ ) if len(lowercase_ ) != len(lowercase_ ): raise ValueError('''Both points must be in the same n-dimensional space''' ) return float(sum(abs(x - y ) for x, y in zip(lowercase_ , lowercase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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( '''--bert_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.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''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.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/config.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/config.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/config.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/config.json''', '''bert-base-multilingual-uncased''': '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json''', '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/config.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/config.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json''' ), '''bert-base-cased-finetuned-mrpc''': '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json''', '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json''', '''bert-base-german-dbmdz-uncased''': '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json''', '''cl-tohoku/bert-base-japanese''': '''https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json''', '''cl-tohoku/bert-base-japanese-whole-word-masking''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json''' ), '''cl-tohoku/bert-base-japanese-char''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json''' ), '''cl-tohoku/bert-base-japanese-char-whole-word-masking''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json''' ), '''wietsedv/bert-base-dutch-cased''': '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json''', # See all BERT models at https://huggingface.co/models?filter=bert } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''bert''' def __init__( self :Optional[int] , _lowerCamelCase :Optional[Any]=3_0_5_2_2 , _lowerCamelCase :int=7_6_8 , _lowerCamelCase :Union[str, Any]=1_2 , _lowerCamelCase :Any=1_2 , _lowerCamelCase :List[str]=3_0_7_2 , _lowerCamelCase :Optional[int]="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :Union[str, Any]=0.1 , _lowerCamelCase :List[str]=5_1_2 , _lowerCamelCase :Union[str, Any]=2 , _lowerCamelCase :Tuple=0.0_2 , _lowerCamelCase :Any=1e-12 , _lowerCamelCase :Tuple=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :Optional[int]=None , **_lowerCamelCase :Optional[Any] , ): super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = vocab_size __SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : List[str] = num_attention_heads __SCREAMING_SNAKE_CASE : str = hidden_act __SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings __SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : int = layer_norm_eps __SCREAMING_SNAKE_CASE : Tuple = position_embedding_type __SCREAMING_SNAKE_CASE : Tuple = use_cache __SCREAMING_SNAKE_CASE : Tuple = classifier_dropout class snake_case ( __UpperCAmelCase ): @property def SCREAMING_SNAKE_CASE_ ( self :Any ): if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE : Dict = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __SCREAMING_SNAKE_CASE : Tuple = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
674
"""simple docstring""" 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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[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] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = 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 , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , 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 , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , 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 SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) 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(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" 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 snake_case : def __init__( self :Dict , _lowerCamelCase :int , _lowerCamelCase :Optional[Any]=1_3 , _lowerCamelCase :Union[str, Any]=3_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :int=3 , _lowerCamelCase :Optional[int]=1_6 , _lowerCamelCase :str=[1, 2, 1] , _lowerCamelCase :int=[2, 2, 4] , _lowerCamelCase :List[Any]=2 , _lowerCamelCase :List[str]=2.0 , _lowerCamelCase :int=True , _lowerCamelCase :Union[str, Any]=0.0 , _lowerCamelCase :Any=0.0 , _lowerCamelCase :Tuple=0.1 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :str=False , _lowerCamelCase :int=True , _lowerCamelCase :Dict=0.0_2 , _lowerCamelCase :Union[str, Any]=1e-5 , _lowerCamelCase :Any=True , _lowerCamelCase :List[str]=None , _lowerCamelCase :List[str]=True , _lowerCamelCase :Dict=1_0 , _lowerCamelCase :Union[str, Any]=8 , _lowerCamelCase :List[Any]=["stage1", "stage2", "stage3"] , _lowerCamelCase :str=[1, 2, 3] , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : Any = image_size __SCREAMING_SNAKE_CASE : Optional[int] = patch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : List[Any] = embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = depths __SCREAMING_SNAKE_CASE : List[str] = num_heads __SCREAMING_SNAKE_CASE : Union[str, Any] = window_size __SCREAMING_SNAKE_CASE : int = mlp_ratio __SCREAMING_SNAKE_CASE : Any = qkv_bias __SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Dict = drop_path_rate __SCREAMING_SNAKE_CASE : Dict = hidden_act __SCREAMING_SNAKE_CASE : Union[str, Any] = use_absolute_embeddings __SCREAMING_SNAKE_CASE : Optional[int] = patch_norm __SCREAMING_SNAKE_CASE : Any = layer_norm_eps __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Dict = is_training __SCREAMING_SNAKE_CASE : Optional[Any] = scope __SCREAMING_SNAKE_CASE : Union[str, Any] = use_labels __SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_stride __SCREAMING_SNAKE_CASE : List[str] = out_features __SCREAMING_SNAKE_CASE : Optional[int] = out_indices def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : int = None if self.use_labels: __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self :int ): 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 SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Dict , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerSwinModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __SCREAMING_SNAKE_CASE : Optional[int] = 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 SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[str] , _lowerCamelCase :Any , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = MaskFormerSwinBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''stem'''] __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerSwinBackbone(config=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = config_and_inputs __SCREAMING_SNAKE_CASE : str = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowerCamelCase__ = {'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {} lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Tuple = MaskFormerSwinModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( '''`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with''' ''' `nn.DataParallel`''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass def SCREAMING_SNAKE_CASE_ ( 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 SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) @unittest.skip('''Swin does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip('''Swin does not support feedforward chunking''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __SCREAMING_SNAKE_CASE : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def SCREAMING_SNAKE_CASE_ ( 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(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : Any = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @unittest.skip(reason='''MaskFormerSwin is only used as backbone and doesn\'t support output_attentions''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormerSwin is only used as an internal backbone''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Dict = outputs.hidden_states __SCREAMING_SNAKE_CASE : int = getattr( self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # 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 : List[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 SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() __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) ) for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Union[str, Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE : Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : int = 3 __SCREAMING_SNAKE_CASE : int = ( 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 : Any = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __SCREAMING_SNAKE_CASE : List[Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (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(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) @unittest.skip(reason='''MaskFormerSwin doesn\'t have pretrained checkpoints''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' ) def SCREAMING_SNAKE_CASE_ ( self :Any ): pass @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : Any = 0 return t def check_equivalence(_lowerCamelCase :Any , _lowerCamelCase :Any , _lowerCamelCase :int , _lowerCamelCase :str={} ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(**_lowerCamelCase , return_dict=_lowerCamelCase , **_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , return_dict=_lowerCamelCase , **_lowerCamelCase ).to_tuple() def recursive_check(_lowerCamelCase :List[str] , _lowerCamelCase :int ): if isinstance(_lowerCamelCase , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_lowerCamelCase , _lowerCamelCase ): recursive_check(_lowerCamelCase , _lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_lowerCamelCase , _lowerCamelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_lowerCamelCase ) , set_nan_tensor_to_zero(_lowerCamelCase ) , 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(_lowerCamelCase ).any()} and `inf`: {torch.isinf(_lowerCamelCase )}. Dict has''' f''' `nan`: {torch.isnan(_lowerCamelCase ).any()} and `inf`: {torch.isinf(_lowerCamelCase )}.''' ) , ) recursive_check(_lowerCamelCase , _lowerCamelCase ) for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : List[str] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : List[Any] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , {'''output_hidden_states''': True} ) __SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , {'''output_hidden_states''': True} ) @require_torch class snake_case ( unittest.TestCase , __UpperCAmelCase ): lowerCamelCase__ = (MaskFormerSwinBackbone,) if is_torch_available() else () lowerCamelCase__ = MaskFormerSwinConfig def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Tuple = MaskFormerSwinModelTester(self ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : List[str] = inputs_dict['''pixel_values'''].shape[0] for backbone_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : int = backbone_class(_lowerCamelCase ) backbone.to(_lowerCamelCase ) backbone.eval() __SCREAMING_SNAKE_CASE : Optional[int] = backbone(**_lowerCamelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _lowerCamelCase ) 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 : str = backbone(**_lowerCamelCase , output_hidden_states=_lowerCamelCase ) 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 : Tuple = 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(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertIsNotNone(outputs.attentions )
674
"""simple docstring""" 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 snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , 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 SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # 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(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # 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 : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, 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 : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[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 : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __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 : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[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 : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : 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 : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = 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 : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, 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 : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # 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 : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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 GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Optional[Any]=None , lowercase_ : str=None ): '''simple docstring''' if attention_mask is None: __SCREAMING_SNAKE_CASE : Optional[int] = tf.cast(tf.math.not_equal(lowercase_ , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class snake_case : lowerCamelCase__ = OPTConfig lowerCamelCase__ = {} lowerCamelCase__ = '''gelu''' def __init__( self :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[Any]=1_3 , _lowerCamelCase :Any=7 , _lowerCamelCase :Any=True , _lowerCamelCase :List[str]=False , _lowerCamelCase :int=9_9 , _lowerCamelCase :Dict=1_6 , _lowerCamelCase :Any=2 , _lowerCamelCase :Any=4 , _lowerCamelCase :Optional[Any]=4 , _lowerCamelCase :Union[str, Any]="gelu" , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Dict=0.1 , _lowerCamelCase :List[str]=2_0 , _lowerCamelCase :int=2 , _lowerCamelCase :str=1 , _lowerCamelCase :Optional[int]=0 , _lowerCamelCase :Union[str, Any]=1_6 , _lowerCamelCase :Optional[Any]=1_6 , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = parent __SCREAMING_SNAKE_CASE : Optional[Any] = batch_size __SCREAMING_SNAKE_CASE : Any = seq_length __SCREAMING_SNAKE_CASE : Any = is_training __SCREAMING_SNAKE_CASE : Optional[int] = use_labels __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Tuple = num_attention_heads __SCREAMING_SNAKE_CASE : str = intermediate_size __SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act __SCREAMING_SNAKE_CASE : List[str] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : Union[str, Any] = eos_token_id __SCREAMING_SNAKE_CASE : Optional[Any] = pad_token_id __SCREAMING_SNAKE_CASE : int = bos_token_id __SCREAMING_SNAKE_CASE : str = embed_dim __SCREAMING_SNAKE_CASE : List[Any] = word_embed_proj_dim __SCREAMING_SNAKE_CASE : str = False def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __SCREAMING_SNAKE_CASE : str = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE : List[Any] = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=_lowerCamelCase , **self.config_updates , ) __SCREAMING_SNAKE_CASE : Optional[int] = prepare_opt_inputs_dict(_lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = TFOPTModel(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[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 : Tuple = 1 # first forward pass __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE : List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __SCREAMING_SNAKE_CASE : int = tf.concat([input_ids, next_tokens] , axis=-1 ) __SCREAMING_SNAKE_CASE : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : List[str] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __SCREAMING_SNAKE_CASE : Tuple = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] __SCREAMING_SNAKE_CASE : Union[str, Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 ) @require_tf class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () lowerCamelCase__ = (TFOPTForCausalLM,) if is_tf_available() else () lowerCamelCase__ = ( {'''feature-extraction''': TFOPTModel, '''text-generation''': TFOPTForCausalLM} if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = 10 def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Any = TFOPTModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(_lowerCamelCase :Any , _lowerCamelCase :Optional[Any] ): if hasattr(_lowerCamelCase , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(_lowerCamelCase , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 1_0, config.vocab_size + 1_0]: # build the embeddings __SCREAMING_SNAKE_CASE : str = model_class(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = _get_word_embedding_weight(_lowerCamelCase , model.get_input_embeddings() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = _get_word_embedding_weight(_lowerCamelCase , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = _get_word_embedding_weight(_lowerCamelCase , model.get_input_embeddings() ) __SCREAMING_SNAKE_CASE : str = _get_word_embedding_weight(_lowerCamelCase , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , _lowerCamelCase ) # check that weights remain the same after resizing __SCREAMING_SNAKE_CASE : int = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __SCREAMING_SNAKE_CASE : List[str] = False self.assertTrue(_lowerCamelCase ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __SCREAMING_SNAKE_CASE : Tuple = False self.assertTrue(_lowerCamelCase ) def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' return tf.constant(lowercase_ , dtype=tf.intaa ) @require_tf class snake_case ( unittest.TestCase ): lowerCamelCase__ = 99 def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = tf.ones((4, 1) , dtype=tf.intaa ) * 2 __SCREAMING_SNAKE_CASE : int = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) __SCREAMING_SNAKE_CASE : List[Any] = input_ids.shape[0] __SCREAMING_SNAKE_CASE : Optional[Any] = OPTConfig( vocab_size=self.vocab_size , hidden_size=2_4 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = TFOPTModel.from_pretrained('''facebook/opt-350m''' ) __SCREAMING_SNAKE_CASE : Any = _long_tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) __SCREAMING_SNAKE_CASE : List[str] = tf.not_equal(_lowerCamelCase , model.config.pad_token_id ) with tf.GradientTape(): __SCREAMING_SNAKE_CASE : Any = model(input_ids=_lowerCamelCase , attention_mask=_lowerCamelCase ).last_hidden_state __SCREAMING_SNAKE_CASE : Dict = (1, 1_1, 5_1_2) self.assertEqual(output.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = tf.constant( [[-0.2_8_7_3, -1.9_2_1_8, -0.3_0_3_3], [-1.2_7_1_0, -0.1_3_3_8, -0.1_9_0_2], [0.4_0_9_5, 0.1_2_1_4, -1.3_1_2_1]] ) self.assertTrue(np.allclose(output[:, :3, :3] , _lowerCamelCase , atol=4e-3 ) ) __SCREAMING_SNAKE_CASE : int = tf.function(_lowerCamelCase , jit_compile=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = xla_generate(_lowerCamelCase , _lowerCamelCase )[0] self.assertTrue(np.allclose(output[:, :3, :3] , _lowerCamelCase , atol=4e-2 ) ) @require_tf @slow class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Dict ): super().setUp() __SCREAMING_SNAKE_CASE : Tuple = '''facebook/opt-350m''' def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = TFOPTForCausalLM.from_pretrained(self.path_model ) __SCREAMING_SNAKE_CASE : Dict = GPTaTokenizer.from_pretrained(self.path_model ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [ '''Today is a beautiful day and I want to''', '''In the city of''', '''Paris is the capital of France and''', '''Computers and mobile phones have taken''', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False __SCREAMING_SNAKE_CASE : Tuple = tokenizer(_lowerCamelCase , return_tensors='''tf''' , padding=_lowerCamelCase , add_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) __SCREAMING_SNAKE_CASE : Optional[Any] = tf.constant( [ [1.3_8_5_1, -1_3.8_9_2_3, -1_0.5_2_2_9, -1_0.7_5_3_3, -0.2_3_0_9, -1_0.2_3_8_4, -0.5_3_6_5, -9.0_9_4_7, -5.1_6_7_0], [-4.7_0_7_3, -1_0.6_2_7_6, -3.9_4_1_5, -2_1.5_2_4_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2], [0.6_2_4_7, -3.4_2_2_9, -8.9_1_7_9, -1.4_2_9_7, -1_4.1_6_5_0, 1.4_1_4_6, -9.0_2_1_8, -0.2_7_0_3, -0.2_7_0_3], [6.4_7_8_3, -1.9_9_1_3, -1_0.7_9_2_6, -2.3_3_3_6, 1.5_0_9_2, -0.9_9_7_4, -6.8_2_1_3, 1.3_4_7_7, 1.3_4_7_7], ] ) self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase , atol=1e-4 ) ) __SCREAMING_SNAKE_CASE : int = tf.function(_lowerCamelCase , jit_compile=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(_lowerCamelCase , _lowerCamelCase , atol=1e-4 ) ) @require_tf @slow class snake_case ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''facebook/opt-125m''' __SCREAMING_SNAKE_CASE : int = [ '''Today is a beautiful day and I want to''', '''In the city of New York, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Any = GPTaTokenizer.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = TFOPTForCausalLM.from_pretrained(_lowerCamelCase ) for prompt in self.prompts: __SCREAMING_SNAKE_CASE : int = tokenizer(_lowerCamelCase , return_tensors='''tf''' ).input_ids __SCREAMING_SNAKE_CASE : int = model.generate(_lowerCamelCase , max_length=1_0 ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.batch_decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) predicted_outputs += generated_string self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Dict = '''facebook/opt-350m''' __SCREAMING_SNAKE_CASE : str = GPTaTokenizer.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFOPTForCausalLM.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''left''' # use different length sentences to test batching __SCREAMING_SNAKE_CASE : Union[str, Any] = [ '''Hello, my dog is a little''', '''Today, I''', ] __SCREAMING_SNAKE_CASE : str = tokenizer(_lowerCamelCase , return_tensors='''tf''' , padding=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inputs['''input_ids'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = model.generate(input_ids=_lowerCamelCase , attention_mask=inputs['''attention_mask'''] ) __SCREAMING_SNAKE_CASE : Any = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids __SCREAMING_SNAKE_CASE : List[Any] = model.generate(input_ids=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) __SCREAMING_SNAKE_CASE : int = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids __SCREAMING_SNAKE_CASE : Optional[int] = model.generate(input_ids=_lowerCamelCase , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer.batch_decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.decode(output_padded[0] , skip_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = [ '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''', '''Today, I was in the middle of a conversation with a friend about the''', ] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) self.assertListEqual(_lowerCamelCase , [non_padded_sentence, padded_sentence] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = '''facebook/opt-350m''' __SCREAMING_SNAKE_CASE : Dict = [ '''Today is a beautiful day and I want to''', '''In the city of San Francisco, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] __SCREAMING_SNAKE_CASE : int = [] __SCREAMING_SNAKE_CASE : Any = GPTaTokenizer.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFOPTForCausalLM.from_pretrained(_lowerCamelCase ) for prompt in self.prompts: __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(_lowerCamelCase , return_tensors='''tf''' ).input_ids __SCREAMING_SNAKE_CASE : List[Any] = model.generate(_lowerCamelCase , max_length=1_0 ) __SCREAMING_SNAKE_CASE : str = tokenizer.batch_decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) predicted_outputs += generated_string self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
674
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class snake_case ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = StableUnCLIPImgaImgPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCamelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCamelCase__ = frozenset([] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : List[Any] = 3_2 __SCREAMING_SNAKE_CASE : Any = embedder_hidden_size # image encoding components __SCREAMING_SNAKE_CASE : int = CLIPImageProcessor(crop_size=3_2 , size=3_2 ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=_lowerCamelCase , projection_dim=_lowerCamelCase , num_hidden_layers=5 , num_attention_heads=4 , image_size=3_2 , intermediate_size=3_7 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Tuple = StableUnCLIPImageNormalizer(embedding_dim=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[str] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_lowerCamelCase , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_lowerCamelCase , layers_per_block=1 , upcast_attention=_lowerCamelCase , use_linear_projection=_lowerCamelCase , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type='''v_prediction''' , set_alpha_to_one=_lowerCamelCase , steps_offset=1 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Any = AutoencoderKL() __SCREAMING_SNAKE_CASE : Optional[int] = { # image encoding components '''feature_extractor''': feature_extractor, '''image_encoder''': image_encoder.eval(), # image noising components '''image_normalizer''': image_normalizer.eval(), '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder.eval(), '''unet''': unet.eval(), '''scheduler''': scheduler, '''vae''': vae.eval(), } return components def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :List[str]=0 , _lowerCamelCase :Optional[int]=True ): if str(_lowerCamelCase ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : str = torch.manual_seed(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) if pil_image: __SCREAMING_SNAKE_CASE : Dict = input_image * 0.5 + 0.5 __SCREAMING_SNAKE_CASE : Optional[Any] = input_image.clamp(0 , 1 ) __SCREAMING_SNAKE_CASE : List[Any] = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __SCREAMING_SNAKE_CASE : Union[str, Any] = DiffusionPipeline.numpy_to_pil(_lowerCamelCase )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : str = self.get_dummy_components() __SCREAMING_SNAKE_CASE : List[str] = StableUnCLIPImgaImgPipeline(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) inputs.update({'''image_embeds''': None} ) __SCREAMING_SNAKE_CASE : str = sd_pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : List[str] = np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = torch_device in ['''cpu''', '''mps'''] self._test_attention_slicing_forward_pass(test_max_difference=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Any = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=_lowerCamelCase ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=_lowerCamelCase ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''' ) __SCREAMING_SNAKE_CASE : List[str] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-l-img2img''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = pipe(_lowerCamelCase , '''anime turle''' , generator=_lowerCamelCase , output_type='''np''' ) __SCREAMING_SNAKE_CASE : str = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : List[str] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''' ) __SCREAMING_SNAKE_CASE : Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy''' ) __SCREAMING_SNAKE_CASE : List[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(_lowerCamelCase , '''anime turle''' , generator=_lowerCamelCase , output_type='''np''' ) __SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE : Any = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : str = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE : int = pipe( _lowerCamelCase , '''anime turtle''' , num_inference_steps=2 , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : Tuple = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = 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=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = 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=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class snake_case ( __UpperCAmelCase ): def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_lowerCamelCase , '''hidden_sizes''' ) ) self.parent.assertTrue(hasattr(_lowerCamelCase , '''num_attention_heads''' ) ) class snake_case : def __init__( self :List[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[int]=1_3 , _lowerCamelCase :Union[str, Any]=6_4 , _lowerCamelCase :Optional[Any]=3 , _lowerCamelCase :Any=3 , _lowerCamelCase :Tuple=2 , _lowerCamelCase :Tuple=1 , _lowerCamelCase :Union[str, Any]=1_6 , _lowerCamelCase :Any=[1_2_8, 2_5_6, 3_8_4] , _lowerCamelCase :Dict=[4, 6, 8] , _lowerCamelCase :List[str]=[2, 3, 4] , _lowerCamelCase :Union[str, Any]=[1_6, 1_6, 1_6] , _lowerCamelCase :Any=0 , _lowerCamelCase :Union[str, Any]=[2, 2, 2] , _lowerCamelCase :List[str]=[2, 2, 2] , _lowerCamelCase :str=0.0_2 , _lowerCamelCase :Dict=True , _lowerCamelCase :List[str]=True , _lowerCamelCase :int=2 , ): __SCREAMING_SNAKE_CASE : Dict = parent __SCREAMING_SNAKE_CASE : List[str] = batch_size __SCREAMING_SNAKE_CASE : Tuple = image_size __SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels __SCREAMING_SNAKE_CASE : Optional[Any] = kernel_size __SCREAMING_SNAKE_CASE : Optional[int] = stride __SCREAMING_SNAKE_CASE : List[str] = padding __SCREAMING_SNAKE_CASE : Tuple = hidden_sizes __SCREAMING_SNAKE_CASE : List[str] = num_attention_heads __SCREAMING_SNAKE_CASE : Optional[Any] = depths __SCREAMING_SNAKE_CASE : Optional[int] = key_dim __SCREAMING_SNAKE_CASE : Optional[int] = drop_path_rate __SCREAMING_SNAKE_CASE : int = patch_size __SCREAMING_SNAKE_CASE : List[str] = attention_ratio __SCREAMING_SNAKE_CASE : List[str] = mlp_ratio __SCREAMING_SNAKE_CASE : int = initializer_range __SCREAMING_SNAKE_CASE : Dict = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] __SCREAMING_SNAKE_CASE : List[Any] = is_training __SCREAMING_SNAKE_CASE : Any = use_labels __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : List[str] = initializer_range def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : List[str] = 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 : Dict = ids_tensor([self.batch_size] , self.num_labels ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self :str ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :str , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Tuple = LevitModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = model(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = (self.image_size, self.image_size) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = image_size[0], image_size[1] for _ in range(4 ): __SCREAMING_SNAKE_CASE : str = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) __SCREAMING_SNAKE_CASE : Tuple = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Tuple , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels __SCREAMING_SNAKE_CASE : Dict = LevitForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = config_and_inputs __SCREAMING_SNAKE_CASE : Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) lowerCamelCase__ = ( { '''feature-extraction''': LevitModel, '''image-classification''': (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = LevitModelTester(self ) __SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return @unittest.skip(reason='''Levit does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): pass @unittest.skip(reason='''Levit does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): pass @unittest.skip(reason='''Levit does not output attentions''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( 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 : Optional[int] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : int = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): def check_hidden_states_output(_lowerCamelCase :List[str] , _lowerCamelCase :List[str] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE : Any = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[str] = outputs.hidden_states __SCREAMING_SNAKE_CASE : List[Any] = len(self.model_tester.depths ) + 1 self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = image_size[0], image_size[1] for _ in range(4 ): __SCREAMING_SNAKE_CASE : Any = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) __SCREAMING_SNAKE_CASE : int = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) __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 : List[str] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :str ): pass def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[Any]=False ): __SCREAMING_SNAKE_CASE : int = super()._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): if not self.model_tester.is_training: return __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE : Optional[Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_lowerCamelCase ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue __SCREAMING_SNAKE_CASE : Optional[Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model(**_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __SCREAMING_SNAKE_CASE : List[Any] = False __SCREAMING_SNAKE_CASE : int = True for model_class in self.all_model_classes: if model_class in get_values(_lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue __SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_lowerCamelCase ) model.gradient_checkpointing_enable() model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model(**_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = 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(_lowerCamelCase ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): 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 : List[Any] = problem_type['''num_labels'''] __SCREAMING_SNAKE_CASE : Optional[Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Dict = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if problem_type["num_labels"] > 1: __SCREAMING_SNAKE_CASE : Optional[int] = inputs['''labels'''].unsqueeze(1 ).repeat(1 , problem_type['''num_labels'''] ) __SCREAMING_SNAKE_CASE : Optional[int] = 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=_lowerCamelCase ) as warning_list: __SCREAMING_SNAKE_CASE : Union[str, Any] = model(**_lowerCamelCase ).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 SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = LevitModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :Any ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Any = prepare_img() __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE : Union[str, Any] = model(**_lowerCamelCase ) # verify the logits __SCREAMING_SNAKE_CASE : List[Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[str] = UNetaDModel( sample_size=(3_2, 6_4) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''') , ) return model @property def SCREAMING_SNAKE_CASE_ ( self :Any ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = UNetaDConditionModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , cross_attention_dim=1_0 , ) return model @property def SCREAMING_SNAKE_CASE_ ( self :Any ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoencoderKL( sample_size=(1_2_8, 6_4) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''') , up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''') , ) __SCREAMING_SNAKE_CASE : List[str] = UNetaDModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''') , ) return vqvae, unet @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : Tuple = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __SCREAMING_SNAKE_CASE : List[str] = DDPMScheduler() __SCREAMING_SNAKE_CASE : Optional[int] = AudioDiffusionPipeline(vqvae=_lowerCamelCase , unet=self.dummy_unet , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.Generator(device=_lowerCamelCase ).manual_seed(4_2 ) __SCREAMING_SNAKE_CASE : Optional[int] = pipe(generator=_lowerCamelCase , steps=4 ) __SCREAMING_SNAKE_CASE : Tuple = output.audios[0] __SCREAMING_SNAKE_CASE : List[Any] = output.images[0] __SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(4_2 ) __SCREAMING_SNAKE_CASE : int = pipe(generator=_lowerCamelCase , steps=4 , return_dict=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __SCREAMING_SNAKE_CASE : List[Any] = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:1_0] __SCREAMING_SNAKE_CASE : int = np.frombuffer(image_from_tuple.tobytes() , dtype='''uint8''' )[:1_0] __SCREAMING_SNAKE_CASE : str = np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __SCREAMING_SNAKE_CASE : Dict = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __SCREAMING_SNAKE_CASE : List[Any] = DDIMScheduler() __SCREAMING_SNAKE_CASE : str = self.dummy_vqvae_and_unet __SCREAMING_SNAKE_CASE : List[str] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) np.random.seed(0 ) __SCREAMING_SNAKE_CASE : int = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(4_2 ) __SCREAMING_SNAKE_CASE : Tuple = pipe(raw_audio=_lowerCamelCase , generator=_lowerCamelCase , start_step=5 , steps=1_0 ) __SCREAMING_SNAKE_CASE : Any = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __SCREAMING_SNAKE_CASE : Any = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:1_0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_unet_condition __SCREAMING_SNAKE_CASE : Dict = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=_lowerCamelCase , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) np.random.seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.rand((1, 1, 1_0) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(generator=_lowerCamelCase , encoding=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = output.images[0] __SCREAMING_SNAKE_CASE : List[Any] = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:1_0] __SCREAMING_SNAKE_CASE : List[str] = np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : str = torch_device __SCREAMING_SNAKE_CASE : Union[str, Any] = DiffusionPipeline.from_pretrained('''teticio/audio-diffusion-ddim-256''' ) __SCREAMING_SNAKE_CASE : int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device=_lowerCamelCase ).manual_seed(4_2 ) __SCREAMING_SNAKE_CASE : Optional[int] = pipe(generator=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = output.audios[0] __SCREAMING_SNAKE_CASE : Union[str, Any] = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __SCREAMING_SNAKE_CASE : Dict = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:1_0] __SCREAMING_SNAKE_CASE : Any = np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
674
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class snake_case ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE_ ( self :Dict ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : int = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE : str = ScoreSdeVeScheduler() __SCREAMING_SNAKE_CASE : str = ScoreSdeVePipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) sde_ve.to(_lowerCamelCase ) sde_ve.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : int = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=_lowerCamelCase , return_dict=_lowerCamelCase )[ 0 ] __SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Any = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : List[str] = '''google/ncsnpp-church-256''' __SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = ScoreSdeVeScheduler.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ScoreSdeVePipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) sde_ve.to(_lowerCamelCase ) sde_ve.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = sde_ve(num_inference_steps=1_0 , output_type='''numpy''' , generator=_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" import os def lowerCAmelCase_ ( lowercase_ : str = "matrix.txt" ): '''simple docstring''' with open(os.path.join(os.path.dirname(lowercase_ ) , lowercase_ ) ) as in_file: __SCREAMING_SNAKE_CASE : List[Any] = in_file.read() __SCREAMING_SNAKE_CASE : Any = [[int(lowercase_ ) for cell in row.split(''',''' )] for row in data.strip().splitlines()] __SCREAMING_SNAKE_CASE : str = [[0 for cell in row] for row in grid] __SCREAMING_SNAKE_CASE : List[Any] = len(grid[0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = [[0 for i in range(lowercase_ )] for j in range(lowercase_ )] __SCREAMING_SNAKE_CASE : Any = grid[0][0] for i in range(1 , lowercase_ ): __SCREAMING_SNAKE_CASE : Dict = grid[0][i] + dp[0][i - 1] for i in range(1 , lowercase_ ): __SCREAMING_SNAKE_CASE : List[str] = grid[i][0] + dp[i - 1][0] for i in range(1 , lowercase_ ): for j in range(1 , lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[int] = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" from __future__ import annotations from math import pi, sqrt def lowerCAmelCase_ ( lowercase_ : float , lowercase_ : float ): '''simple docstring''' if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = KandinskyVaaControlnetImgaImgPipeline lowerCamelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint'''] lowerCamelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint'''] lowerCamelCase__ = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] lowerCamelCase__ = False @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return 3_2 @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return 3_2 @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.time_input_dim @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return 1_0_0 @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''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 : int = UNetaDConditionModel(**_lowerCamelCase ) return model @property def SCREAMING_SNAKE_CASE_ ( self :Any ): return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Any = VQModel(**self.dummy_movq_kwargs ) return model def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : int = self.dummy_unet __SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_movq __SCREAMING_SNAKE_CASE : Optional[Any] = { '''num_train_timesteps''': 1_0_0_0, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_0_0_8_5, '''beta_end''': 0.0_1_2, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } __SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=0 ): __SCREAMING_SNAKE_CASE : Any = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _lowerCamelCase ) # create init_image __SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE : Optional[int] = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('''RGB''' ).resize((2_5_6, 2_5_6) ) # create hint __SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) if str(_lowerCamelCase ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : str = torch.manual_seed(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = { '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 6_4, '''width''': 6_4, '''num_inference_steps''': 1_0, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = '''cpu''' __SCREAMING_SNAKE_CASE : str = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Optional[int] = self.pipeline_class(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = pipe(**self.get_dummy_inputs(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = output.images __SCREAMING_SNAKE_CASE : Dict = pipe( **self.get_dummy_inputs(_lowerCamelCase ) , return_dict=_lowerCamelCase , )[0] __SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [0.5_4_9_8_5_0_3_4, 0.5_5_5_0_9_3_6_5, 0.5_2_5_6_1_5_0_4, 0.5_5_7_0_4_9_4, 0.5_5_9_3_8_1_8, 0.5_2_6_3_9_7_9, 0.5_0_2_8_5_6_4_3, 0.5_0_6_9_8_4_6, 0.5_1_1_9_6_7_3_6] ) 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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy''' ) __SCREAMING_SNAKE_CASE : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) __SCREAMING_SNAKE_CASE : Any = init_image.resize((5_1_2, 5_1_2) ) __SCREAMING_SNAKE_CASE : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) __SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(np.array(_lowerCamelCase ) ).float() / 2_5_5.0 __SCREAMING_SNAKE_CASE : Any = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) __SCREAMING_SNAKE_CASE : Dict = '''A robot, 4k photo''' __SCREAMING_SNAKE_CASE : Union[str, Any] = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline.to(_lowerCamelCase ) pipeline.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = pipe_prior( _lowerCamelCase , image=_lowerCamelCase , strength=0.8_5 , generator=_lowerCamelCase , negative_prompt='''''' , ).to_tuple() __SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline( image=_lowerCamelCase , image_embeds=_lowerCamelCase , negative_image_embeds=_lowerCamelCase , hint=_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=1_0_0 , height=5_1_2 , width=5_1_2 , strength=0.5 , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : Optional[Any] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase )
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = emb.weight.shape __SCREAMING_SNAKE_CASE : List[str] = nn.Linear(lowercase_ , lowercase_ , bias=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = emb.weight.data return lin_layer def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Union[str, Any]="facebook/mbart-large-en-ro" , lowercase_ : Any=False , lowercase_ : int=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = torch.load(lowercase_ , map_location='''cpu''' )['''model'''] remove_ignore_keys_(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = state_dict['''encoder.embed_tokens.weight'''].shape[0] __SCREAMING_SNAKE_CASE : Any = MBartConfig.from_pretrained(lowercase_ , vocab_size=lowercase_ ) if mbart_aa and finetuned: __SCREAMING_SNAKE_CASE : str = '''relu''' __SCREAMING_SNAKE_CASE : Optional[Any] = state_dict['''decoder.embed_tokens.weight'''] __SCREAMING_SNAKE_CASE : Any = MBartForConditionalGeneration(lowercase_ ) model.model.load_state_dict(lowercase_ ) if finetuned: __SCREAMING_SNAKE_CASE : Optional[Any] = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a 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.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') _lowerCamelCase = parser.parse_args() _lowerCamelCase = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=_lowerCamelCase , ) assert hasattr(self , '''env''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Union[str, Any] ): # configuration for running training on smdistributed Model Parallel __SCREAMING_SNAKE_CASE : List[str] = { '''enabled''': True, '''processes_per_host''': 8, } __SCREAMING_SNAKE_CASE : int = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __SCREAMING_SNAKE_CASE : List[Any] = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __SCREAMING_SNAKE_CASE : Union[str, Any] = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=_lowerCamelCase , instance_type=self.instance_type , debugger_hook_config=_lowerCamelCase , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_0_0, } , metric_definitions=self.env.metric_definitions , distribution=_lowerCamelCase , py_version='''py36''' , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Optional[int] ): TrainingJobAnalytics(_lowerCamelCase ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Dict ): # create estimator __SCREAMING_SNAKE_CASE : str = self.create_estimator(_lowerCamelCase ) # run training estimator.fit() # result dataframe __SCREAMING_SNAKE_CASE : int = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __SCREAMING_SNAKE_CASE : int = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __SCREAMING_SNAKE_CASE : Any = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __SCREAMING_SNAKE_CASE : str = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , _lowerCamelCase )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = MobileBertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Any = MobileBertForPreTraining(lowercase_ ) # Load weights from tf checkpoint __SCREAMING_SNAKE_CASE : str = load_tf_weights_in_mobilebert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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( '''--mobilebert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained MobileBERT 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.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
674
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer 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.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import math import sys def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = '''''' try: with open(lowercase_ , '''rb''' ) as binary_file: __SCREAMING_SNAKE_CASE : Dict = binary_file.read() for dat in data: __SCREAMING_SNAKE_CASE : Optional[int] = F'''{dat:08b}''' result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = {'''0''': '''0''', '''1''': '''1'''} __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = '''''', '''''' __SCREAMING_SNAKE_CASE : Tuple = len(lowercase_ ) for i in range(len(lowercase_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __SCREAMING_SNAKE_CASE : int = lexicon[curr_string] result += last_match_id __SCREAMING_SNAKE_CASE : str = last_match_id + '''0''' if math.loga(lowercase_ ).is_integer(): __SCREAMING_SNAKE_CASE : Optional[Any] = {} for curr_key in list(lowercase_ ): __SCREAMING_SNAKE_CASE : List[Any] = lexicon.pop(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = new_lex __SCREAMING_SNAKE_CASE : Dict = last_match_id + '''1''' index += 1 __SCREAMING_SNAKE_CASE : List[Any] = '''''' return result def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = 8 try: with open(lowercase_ , '''wb''' ) as opened_file: __SCREAMING_SNAKE_CASE : str = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase_ ) , lowercase_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase_ , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for letter in data_bits: if letter == "1": break counter += 1 __SCREAMING_SNAKE_CASE : Tuple = data_bits[counter:] __SCREAMING_SNAKE_CASE : int = data_bits[counter + 1 :] return data_bits def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = read_file_binary(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = remove_prefix(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = decompress_data(lowercase_ ) write_file_binary(lowercase_ , lowercase_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' assert isinstance(lowercase_ , lowercase_ ), F'''The input value of [n={number}] is not an integer''' if number == 1: return 2 elif number < 1: __SCREAMING_SNAKE_CASE : Union[str, Any] = F'''The input value of [n={number}] has to be > 0''' raise ValueError(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Tuple = sylvester(number - 1 ) __SCREAMING_SNAKE_CASE : Any = num - 1 __SCREAMING_SNAKE_CASE : Tuple = num return lower * upper + 1 if __name__ == "__main__": print(f'The 8th number in Sylvester\'s sequence: {sylvester(8)}')
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] __SCREAMING_SNAKE_CASE : str = 6 __SCREAMING_SNAKE_CASE : int = 1 __SCREAMING_SNAKE_CASE : List[Any] = 1901 __SCREAMING_SNAKE_CASE : Optional[int] = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 __SCREAMING_SNAKE_CASE : Optional[Any] = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 __SCREAMING_SNAKE_CASE : Optional[Any] = day - 29 else: if day > days_per_month[month - 1]: month += 1 __SCREAMING_SNAKE_CASE : Optional[int] = day - days_per_month[month - 2] if month > 12: year += 1 __SCREAMING_SNAKE_CASE : Any = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
674
"""simple docstring""" 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 _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = 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=3_84, 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=1_28, 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''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = 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) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 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 _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 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) _lowerCamelCase = 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) _lowerCamelCase = 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_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[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 : Tuple = 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 : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (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. _lowerCamelCase = 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. _lowerCamelCase = 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. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = 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}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [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 : Optional[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 : Optional[int] = 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 : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 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 : str = 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 : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = 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''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = 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 : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = 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_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = 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}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = 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 * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''openai-gpt''' lowerCamelCase__ = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self :str , _lowerCamelCase :Union[str, Any]=4_0_4_7_8 , _lowerCamelCase :Dict=5_1_2 , _lowerCamelCase :Dict=7_6_8 , _lowerCamelCase :Tuple=1_2 , _lowerCamelCase :List[Any]=1_2 , _lowerCamelCase :Union[str, Any]="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :Tuple=0.1 , _lowerCamelCase :Optional[Any]=1e-5 , _lowerCamelCase :Union[str, Any]=0.0_2 , _lowerCamelCase :int="cls_index" , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=None , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=0.1 , **_lowerCamelCase :List[Any] , ): __SCREAMING_SNAKE_CASE : Tuple = vocab_size __SCREAMING_SNAKE_CASE : Any = n_positions __SCREAMING_SNAKE_CASE : Dict = n_embd __SCREAMING_SNAKE_CASE : Union[str, Any] = n_layer __SCREAMING_SNAKE_CASE : Union[str, Any] = n_head __SCREAMING_SNAKE_CASE : Optional[Any] = afn __SCREAMING_SNAKE_CASE : Tuple = resid_pdrop __SCREAMING_SNAKE_CASE : int = embd_pdrop __SCREAMING_SNAKE_CASE : int = attn_pdrop __SCREAMING_SNAKE_CASE : List[Any] = layer_norm_epsilon __SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range __SCREAMING_SNAKE_CASE : List[str] = summary_type __SCREAMING_SNAKE_CASE : str = summary_use_proj __SCREAMING_SNAKE_CASE : List[Any] = summary_activation __SCREAMING_SNAKE_CASE : Tuple = summary_first_dropout __SCREAMING_SNAKE_CASE : List[Any] = summary_proj_to_labels super().__init__(**_lowerCamelCase )
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class snake_case ( __UpperCAmelCase ): def __init__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[Any] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Optional[int] ): self.events.append('''on_init_end''' ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Tuple , _lowerCamelCase :List[Any] , _lowerCamelCase :Dict , **_lowerCamelCase :Dict ): self.events.append('''on_train_begin''' ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Dict , _lowerCamelCase :Optional[int] , _lowerCamelCase :int , **_lowerCamelCase :Any ): self.events.append('''on_train_end''' ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Dict , _lowerCamelCase :List[Any] , **_lowerCamelCase :List[Any] ): self.events.append('''on_epoch_begin''' ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Dict , **_lowerCamelCase :List[str] ): self.events.append('''on_epoch_end''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[int] , **_lowerCamelCase :List[Any] ): self.events.append('''on_step_begin''' ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[str] , _lowerCamelCase :int , _lowerCamelCase :Optional[int] , **_lowerCamelCase :str ): self.events.append('''on_step_end''' ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[int] , **_lowerCamelCase :int ): self.events.append('''on_evaluate''' ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Tuple , _lowerCamelCase :Tuple , _lowerCamelCase :Tuple , **_lowerCamelCase :Dict ): self.events.append('''on_predict''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :int , _lowerCamelCase :int , **_lowerCamelCase :str ): self.events.append('''on_save''' ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Dict , _lowerCamelCase :List[Any] , _lowerCamelCase :str , **_lowerCamelCase :int ): self.events.append('''on_log''' ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :List[str] , _lowerCamelCase :int , _lowerCamelCase :List[str] , **_lowerCamelCase :List[str] ): self.events.append('''on_prediction_step''' ) @require_torch class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): shutil.rmtree(self.output_dir ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Optional[int]=0 , _lowerCamelCase :Optional[int]=0 , _lowerCamelCase :Optional[Any]=6_4 , _lowerCamelCase :Optional[int]=6_4 , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :Dict=False , **_lowerCamelCase :int ): # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __SCREAMING_SNAKE_CASE : Tuple = RegressionDataset(length=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = RegressionDataset(length=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = RegressionModelConfig(a=_lowerCamelCase , b=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = RegressionPreTrainedModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = TrainingArguments(self.output_dir , disable_tqdm=_lowerCamelCase , report_to=[] , **_lowerCamelCase ) return Trainer( _lowerCamelCase , _lowerCamelCase , train_dataset=_lowerCamelCase , eval_dataset=_lowerCamelCase , callbacks=_lowerCamelCase , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Optional[int] ): self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) # Order doesn't matter __SCREAMING_SNAKE_CASE : Union[str, Any] = sorted(_lowerCamelCase , key=lambda _lowerCamelCase : cb.__name__ if isinstance(_lowerCamelCase , _lowerCamelCase ) else cb.__class__.__name__ ) __SCREAMING_SNAKE_CASE : List[Any] = sorted(_lowerCamelCase , key=lambda _lowerCamelCase : cb.__name__ if isinstance(_lowerCamelCase , _lowerCamelCase ) else cb.__class__.__name__ ) for cba, cba in zip(_lowerCamelCase , _lowerCamelCase ): if isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(_lowerCamelCase , _lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ) and not isinstance(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(_lowerCamelCase , cba.__class__ ) elif not isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(cba.__class__ , _lowerCamelCase ) else: self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''on_init_end''', '''on_train_begin'''] __SCREAMING_SNAKE_CASE : Dict = 0 __SCREAMING_SNAKE_CASE : str = len(trainer.get_eval_dataloader() ) __SCREAMING_SNAKE_CASE : Tuple = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(_lowerCamelCase ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = self.get_trainer() __SCREAMING_SNAKE_CASE : Optional[Any] = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) # Callbacks passed at init are added to the default callbacks __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(_lowerCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __SCREAMING_SNAKE_CASE : Any = self.get_trainer(disable_tqdm=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __SCREAMING_SNAKE_CASE : Optional[int] = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(_lowerCamelCase ) expected_callbacks.remove(_lowerCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_trainer() __SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.pop_callback(_lowerCamelCase ) self.assertEqual(cb.__class__ , _lowerCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) trainer.add_callback(_lowerCamelCase ) expected_callbacks.insert(0 , _lowerCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) # We can also add, pop, or remove by instance __SCREAMING_SNAKE_CASE : Tuple = self.get_trainer() __SCREAMING_SNAKE_CASE : Optional[Any] = trainer.callback_handler.callbacks[0] trainer.remove_callback(_lowerCamelCase ) expected_callbacks.remove(_lowerCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = self.get_trainer() __SCREAMING_SNAKE_CASE : int = trainer.callback_handler.callbacks[0] __SCREAMING_SNAKE_CASE : Tuple = trainer.pop_callback(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) trainer.add_callback(_lowerCamelCase ) expected_callbacks.insert(0 , _lowerCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __SCREAMING_SNAKE_CASE : Dict = trainer.callback_handler.callbacks[-2].events self.assertEqual(_lowerCamelCase , self.get_expected_events(_lowerCamelCase ) ) # Independent log/save/eval __SCREAMING_SNAKE_CASE : List[str] = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __SCREAMING_SNAKE_CASE : List[str] = trainer.callback_handler.callbacks[-2].events self.assertEqual(_lowerCamelCase , self.get_expected_events(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : int = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __SCREAMING_SNAKE_CASE : List[str] = trainer.callback_handler.callbacks[-2].events self.assertEqual(_lowerCamelCase , self.get_expected_events(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.callback_handler.callbacks[-2].events self.assertEqual(_lowerCamelCase , self.get_expected_events(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __SCREAMING_SNAKE_CASE : int = trainer.callback_handler.callbacks[-2].events self.assertEqual(_lowerCamelCase , self.get_expected_events(_lowerCamelCase ) ) # A bit of everything __SCREAMING_SNAKE_CASE : Optional[int] = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=1_0 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __SCREAMING_SNAKE_CASE : str = trainer.callback_handler.callbacks[-2].events self.assertEqual(_lowerCamelCase , self.get_expected_events(_lowerCamelCase ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __SCREAMING_SNAKE_CASE : str = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(_lowerCamelCase ) in warn_mock.call_args[0][0]
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = 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(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) 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 if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = 1 __SCREAMING_SNAKE_CASE : Dict = 3 __SCREAMING_SNAKE_CASE : Dict = (3_2, 3_2) __SCREAMING_SNAKE_CASE : Any = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_lowerCamelCase ) return image @property def SCREAMING_SNAKE_CASE_ ( self :int ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , ) return model @property def SCREAMING_SNAKE_CASE_ ( self :str ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) return model @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_6 , ) return RobertaSeriesModelWithTransformation(_lowerCamelCase ) @property def SCREAMING_SNAKE_CASE_ ( self :Any ): def extract(*_lowerCamelCase :str , **_lowerCamelCase :Optional[Any] ): class snake_case : def __init__( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.ones([0] ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :int ): self.pixel_values.to(_lowerCamelCase ) return self return Out() return extract def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE : Any = self.dummy_cond_unet __SCREAMING_SNAKE_CASE : List[str] = PNDMScheduler(skip_prk_steps=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = self.dummy_vae __SCREAMING_SNAKE_CASE : Tuple = self.dummy_text_encoder __SCREAMING_SNAKE_CASE : Optional[Any] = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) __SCREAMING_SNAKE_CASE : int = 7_7 __SCREAMING_SNAKE_CASE : List[str] = self.dummy_image.to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk __SCREAMING_SNAKE_CASE : Union[str, Any] = AltDiffusionImgaImgPipeline( unet=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , safety_checker=_lowerCamelCase , feature_extractor=self.dummy_extractor , ) __SCREAMING_SNAKE_CASE : Optional[int] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = alt_pipe.to(_lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''A painting of a squirrel eating a burger''' __SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = alt_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Any = output.images __SCREAMING_SNAKE_CASE : str = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = alt_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=_lowerCamelCase , return_dict=_lowerCamelCase , )[0] __SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = self.dummy_cond_unet __SCREAMING_SNAKE_CASE : Optional[Any] = PNDMScheduler(skip_prk_steps=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = self.dummy_vae __SCREAMING_SNAKE_CASE : str = self.dummy_text_encoder __SCREAMING_SNAKE_CASE : Dict = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) __SCREAMING_SNAKE_CASE : List[str] = 7_7 __SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_image.to(_lowerCamelCase ) # put models in fp16 __SCREAMING_SNAKE_CASE : Union[str, Any] = unet.half() __SCREAMING_SNAKE_CASE : str = vae.half() __SCREAMING_SNAKE_CASE : Dict = bert.half() # make sure here that pndm scheduler skips prk __SCREAMING_SNAKE_CASE : Optional[int] = AltDiffusionImgaImgPipeline( unet=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , safety_checker=_lowerCamelCase , feature_extractor=self.dummy_extractor , ) __SCREAMING_SNAKE_CASE : str = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = alt_pipe.to(_lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = '''A painting of a squirrel eating a burger''' __SCREAMING_SNAKE_CASE : Any = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Any = alt_pipe( [prompt] , generator=_lowerCamelCase , num_inference_steps=2 , output_type='''np''' , image=_lowerCamelCase , ).images assert image.shape == (1, 3_2, 3_2, 3) @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : int = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) # resize to resolution that is divisible by 8 but not 16 or 32 __SCREAMING_SNAKE_CASE : Any = init_image.resize((7_6_0, 5_0_4) ) __SCREAMING_SNAKE_CASE : List[Any] = '''BAAI/AltDiffusion''' __SCREAMING_SNAKE_CASE : Optional[Any] = AltDiffusionImgaImgPipeline.from_pretrained( _lowerCamelCase , safety_checker=_lowerCamelCase , ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE : Optional[int] = '''A fantasy landscape, trending on artstation''' __SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , generator=_lowerCamelCase , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : str = output.images[0] __SCREAMING_SNAKE_CASE : Union[str, Any] = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert image.shape == (5_0_4, 7_6_0, 3) __SCREAMING_SNAKE_CASE : str = np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) __SCREAMING_SNAKE_CASE : List[str] = init_image.resize((7_6_8, 5_1_2) ) __SCREAMING_SNAKE_CASE : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''' ) __SCREAMING_SNAKE_CASE : List[str] = '''BAAI/AltDiffusion''' __SCREAMING_SNAKE_CASE : Dict = AltDiffusionImgaImgPipeline.from_pretrained( _lowerCamelCase , safety_checker=_lowerCamelCase , ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE : List[str] = '''A fantasy landscape, trending on artstation''' __SCREAMING_SNAKE_CASE : Optional[int] = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , generator=_lowerCamelCase , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : List[str] = output.images[0] assert image.shape == (5_1_2, 7_6_8, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( lowercase_ : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = SwinConfig( embed_dim=192 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['''stage2''', '''stage3''', '''stage4'''] , ) __SCREAMING_SNAKE_CASE : Dict = DetaConfig( backbone_config=lowercase_ , num_queries=900 , encoder_ffn_dim=2048 , decoder_ffn_dim=2048 , num_feature_levels=5 , assign_first_stage=lowercase_ , with_box_refine=lowercase_ , two_stage=lowercase_ , ) # set labels __SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files''' if "o365" in model_name: __SCREAMING_SNAKE_CASE : int = 366 __SCREAMING_SNAKE_CASE : Any = '''object365-id2label.json''' else: __SCREAMING_SNAKE_CASE : List[str] = 91 __SCREAMING_SNAKE_CASE : str = '''coco-detection-id2label.json''' __SCREAMING_SNAKE_CASE : Dict = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(open(cached_download(hf_hub_url(lowercase_ , lowercase_ , repo_type='''dataset''' ) ) , '''r''' ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = {int(lowercase_ ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : Optional[int] = idalabel __SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = [] # stem # fmt: off rename_keys.append(('''backbone.0.body.patch_embed.proj.weight''', '''model.backbone.model.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.proj.bias''', '''model.backbone.model.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.weight''', '''model.backbone.model.embeddings.norm.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.bias''', '''model.backbone.model.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append(('''backbone.0.body.norm1.weight''', '''model.backbone.model.hidden_states_norms.stage2.weight''') ) rename_keys.append(('''backbone.0.body.norm1.bias''', '''model.backbone.model.hidden_states_norms.stage2.bias''') ) rename_keys.append(('''backbone.0.body.norm2.weight''', '''model.backbone.model.hidden_states_norms.stage3.weight''') ) rename_keys.append(('''backbone.0.body.norm2.bias''', '''model.backbone.model.hidden_states_norms.stage3.bias''') ) rename_keys.append(('''backbone.0.body.norm3.weight''', '''model.backbone.model.hidden_states_norms.stage4.weight''') ) rename_keys.append(('''backbone.0.body.norm3.bias''', '''model.backbone.model.hidden_states_norms.stage4.bias''') ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias''') ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias''') ) # fmt: on return rename_keys def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = dct.pop(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = val def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __SCREAMING_SNAKE_CASE : str = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight''' ) __SCREAMING_SNAKE_CASE : int = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __SCREAMING_SNAKE_CASE : str = in_proj_weight[:dim, :] __SCREAMING_SNAKE_CASE : int = in_proj_bias[: dim] __SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[ dim : dim * 2, : ] __SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : Dict = in_proj_weight[ -dim :, : ] __SCREAMING_SNAKE_CASE : List[str] = in_proj_bias[-dim :] # fmt: on def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention __SCREAMING_SNAKE_CASE : int = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict __SCREAMING_SNAKE_CASE : str = in_proj_weight[:hidden_size, :] __SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[:hidden_size] __SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[ hidden_size : hidden_size * 2, : ] __SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias[hidden_size : hidden_size * 2] __SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[-hidden_size:, :] __SCREAMING_SNAKE_CASE : Tuple = in_proj_bias[-hidden_size:] def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(requests.get(lowercase_ , stream=lowercase_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Tuple , lowercase_ : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = get_deta_config(lowercase_ ) # load original state dict if model_name == "deta-swin-large": __SCREAMING_SNAKE_CASE : Union[str, Any] = hf_hub_download(repo_id='''nielsr/deta-checkpoints''' , filename='''adet_swin_ft.pth''' ) elif model_name == "deta-swin-large-o365": __SCREAMING_SNAKE_CASE : Any = hf_hub_download(repo_id='''jozhang97/deta-swin-l-o365''' , filename='''deta_swin_pt_o365.pth''' ) else: raise ValueError(F'''Model name {model_name} not supported''' ) __SCREAMING_SNAKE_CASE : List[Any] = torch.load(lowercase_ , map_location='''cpu''' )['''model'''] # original state dict for name, param in state_dict.items(): print(lowercase_ , param.shape ) # rename keys __SCREAMING_SNAKE_CASE : List[Any] = create_rename_keys(lowercase_ ) for src, dest in rename_keys: rename_key(lowercase_ , lowercase_ , lowercase_ ) read_in_swin_q_k_v(lowercase_ , config.backbone_config ) read_in_decoder_q_k_v(lowercase_ , lowercase_ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: __SCREAMING_SNAKE_CASE : str = state_dict.pop(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = val if "input_proj" in key: __SCREAMING_SNAKE_CASE : Any = state_dict.pop(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: __SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = val # finally, create HuggingFace model and load state dict __SCREAMING_SNAKE_CASE : int = DetaForObjectDetection(lowercase_ ) model.load_state_dict(lowercase_ ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = '''cuda''' if torch.cuda.is_available() else '''cpu''' model.to(lowercase_ ) # load image processor __SCREAMING_SNAKE_CASE : int = DetaImageProcessor(format='''coco_detection''' ) # verify our conversion on image __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : Optional[int] = processor(images=lowercase_ , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Optional[int] = encoding['''pixel_values'''] __SCREAMING_SNAKE_CASE : Dict = model(pixel_values.to(lowercase_ ) ) # verify logits print('''Logits:''' , outputs.logits[0, :3, :3] ) print('''Boxes:''' , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": __SCREAMING_SNAKE_CASE : int = torch.tensor( [[-7.6_308, -2.8_485, -5.3_737], [-7.2_037, -4.5_505, -4.8_027], [-7.2_943, -4.2_611, -4.6_617]] ) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[0.4_987, 0.4_969, 0.9_999], [0.2_549, 0.5_498, 0.4_805], [0.5_498, 0.2_757, 0.0_569]] ) elif model_name == "deta-swin-large-o365": __SCREAMING_SNAKE_CASE : str = torch.tensor( [[-8.0_122, -3.5_720, -4.9_717], [-8.1_547, -3.6_886, -4.6_389], [-7.6_610, -3.6_194, -5.0_134]] ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([[0.2_523, 0.5_549, 0.4_881], [0.7_715, 0.4_149, 0.4_601], [0.5_503, 0.2_753, 0.0_575]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(lowercase_ ) , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(lowercase_ ) , atol=1E-4 ) print('''Everything ok!''' ) if pytorch_dump_folder_path: # Save model and processor logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...''' ) Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) # Push to hub if push_to_hub: print('''Pushing model and processor to hub...''' ) model.push_to_hub(F'''jozhang97/{model_name}''' ) processor.push_to_hub(F'''jozhang97/{model_name}''' ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '''--model_name''', type=str, default='''deta-swin-large''', choices=['''deta-swin-large''', '''deta-swin-large-o365'''], help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _lowerCamelCase = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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( '''--bert_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.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : list[str] | None = None ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = word_bank or [] # create a table __SCREAMING_SNAKE_CASE : int = len(lowercase_ ) + 1 __SCREAMING_SNAKE_CASE : list[list[list[str]]] = [] for _ in range(lowercase_ ): table.append([] ) # seed value __SCREAMING_SNAKE_CASE : Optional[Any] = [[]] # because empty string has empty combination # iterate through the indices for i in range(lowercase_ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(lowercase_ )] == word: __SCREAMING_SNAKE_CASE : list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(lowercase_ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(lowercase_ )]: combination.reverse() return table[len(lowercase_ )] if __name__ == "__main__": print(all_construct('''jwajalapa''', ['''jwa''', '''j''', '''w''', '''a''', '''la''', '''lapa'''])) print(all_construct('''rajamati''', ['''s''', '''raj''', '''amat''', '''raja''', '''ma''', '''i''', '''t'''])) print( all_construct( '''hexagonosaurus''', ['''h''', '''ex''', '''hex''', '''ag''', '''ago''', '''ru''', '''auru''', '''rus''', '''go''', '''no''', '''o''', '''s'''], ) )
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''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.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = args.pruning_method __SCREAMING_SNAKE_CASE : Dict = args.threshold __SCREAMING_SNAKE_CASE : str = args.model_name_or_path.rstrip('''/''' ) __SCREAMING_SNAKE_CASE : List[Any] = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.load(os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) __SCREAMING_SNAKE_CASE : List[Any] = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __SCREAMING_SNAKE_CASE : List[Any] = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: __SCREAMING_SNAKE_CASE : Tuple = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: __SCREAMING_SNAKE_CASE : str = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": __SCREAMING_SNAKE_CASE : Tuple = MagnitudeBinarizer.apply(inputs=lowercase_ , threshold=lowercase_ ) __SCREAMING_SNAKE_CASE : Any = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue __SCREAMING_SNAKE_CASE : List[str] = name[:-6] __SCREAMING_SNAKE_CASE : str = model[F'''{prefix_}mask_scores'''] __SCREAMING_SNAKE_CASE : List[str] = TopKBinarizer.apply(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __SCREAMING_SNAKE_CASE : Optional[Any] = name[:-6] __SCREAMING_SNAKE_CASE : Optional[Any] = model[F'''{prefix_}mask_scores'''] __SCREAMING_SNAKE_CASE : Optional[int] = ThresholdBinarizer.apply(lowercase_ , lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue __SCREAMING_SNAKE_CASE : Tuple = name[:-6] __SCREAMING_SNAKE_CASE : int = model[F'''{prefix_}mask_scores'''] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = -0.1, 1.1 __SCREAMING_SNAKE_CASE : List[str] = torch.sigmoid(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = s * (r - l) + l __SCREAMING_SNAKE_CASE : Dict = s_bar.clamp(min=0.0 , max=1.0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError('''Unknown pruning method''' ) if target_model_path is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join( os.path.dirname(lowercase_ ) , F'''bertarized_{os.path.basename(lowercase_ )}''' ) if not os.path.isdir(lowercase_ ): shutil.copytree(lowercase_ , lowercase_ ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(lowercase_ , os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) print('''\nPruned model saved! See you later!''' ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '''--pruning_method''', choices=['''l0''', '''magnitude''', '''topK''', '''sigmoied_threshold'''], type=str, required=True, help=( '''Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,''' ''' sigmoied_threshold = Soft movement pruning)''' ), ) parser.add_argument( '''--threshold''', type=float, required=False, help=( '''For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.''' '''For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.''' '''Not needed for `l0`''' ), ) parser.add_argument( '''--model_name_or_path''', type=str, required=True, help='''Folder containing the model that was previously fine-pruned''', ) parser.add_argument( '''--target_model_path''', default=None, type=str, required=False, help='''Folder containing the model that was previously fine-pruned''', ) _lowerCamelCase = parser.parse_args() main(args)
674
"""simple docstring""" 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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[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] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = 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 , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , 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 , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , 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 SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) 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(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''', } class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): lowerCamelCase__ = '''resnet''' lowerCamelCase__ = ['''basic''', '''bottleneck'''] def __init__( self :Tuple , _lowerCamelCase :Tuple=3 , _lowerCamelCase :Any=6_4 , _lowerCamelCase :Optional[Any]=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , _lowerCamelCase :List[Any]=[3, 4, 6, 3] , _lowerCamelCase :List[str]="bottleneck" , _lowerCamelCase :List[Any]="relu" , _lowerCamelCase :Optional[Any]=False , _lowerCamelCase :Tuple=None , _lowerCamelCase :str=None , **_lowerCamelCase :Optional[int] , ): super().__init__(**_lowerCamelCase ) if layer_type not in self.layer_types: raise ValueError(f'''layer_type={layer_type} is not one of {','.join(self.layer_types )}''' ) __SCREAMING_SNAKE_CASE : List[Any] = num_channels __SCREAMING_SNAKE_CASE : List[str] = embedding_size __SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_sizes __SCREAMING_SNAKE_CASE : List[str] = depths __SCREAMING_SNAKE_CASE : Optional[int] = layer_type __SCREAMING_SNAKE_CASE : Dict = hidden_act __SCREAMING_SNAKE_CASE : int = downsample_in_first_stage __SCREAMING_SNAKE_CASE : int = ['''stem'''] + [f'''stage{idx}''' for idx in range(1 , len(_lowerCamelCase ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return 1e-3
674
"""simple docstring""" 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 snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , 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 SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # 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(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # 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 : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, 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 : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[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 : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __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 : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[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 : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : 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 : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = 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 : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, 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 : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # 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 : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class snake_case ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE_ ( self :Any ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE : int = PNDMScheduler() __SCREAMING_SNAKE_CASE : Optional[int] = PNDMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) pndm.to(_lowerCamelCase ) pndm.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = pndm(generator=_lowerCamelCase , num_inference_steps=2_0 , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = pndm(generator=_lowerCamelCase , num_inference_steps=2_0 , output_type='''numpy''' , return_dict=_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : List[str] = '''google/ddpm-cifar10-32''' __SCREAMING_SNAKE_CASE : Tuple = UNetaDModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = PNDMScheduler() __SCREAMING_SNAKE_CASE : Optional[int] = PNDMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) pndm.to(_lowerCamelCase ) pndm.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Tuple = pndm(generator=_lowerCamelCase , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : Dict = np.array([0.1_5_6_4, 0.1_4_6_4_5, 0.1_4_0_6, 0.1_4_7_1_5, 0.1_2_4_2_5, 0.1_4_0_4_5, 0.1_3_1_1_5, 0.1_2_1_7_5, 0.1_2_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
674
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration _lowerCamelCase = pytest.mark.integration _lowerCamelCase = {'''comet'''} _lowerCamelCase = importlib.util.find_spec('''fairseq''') is not None _lowerCamelCase = {'''code_eval'''} _lowerCamelCase = os.name == '''nt''' _lowerCamelCase = {'''bertscore''', '''frugalscore''', '''perplexity'''} _lowerCamelCase = importlib.util.find_spec('''transformers''') is not None def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' @wraps(lowercase_ ) def wrapper(self : Optional[Any] , lowercase_ : Dict ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('''"test requires Fairseq"''' ) else: test_case(self , lowercase_ ) return wrapper def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' @wraps(lowercase_ ) def wrapper(self : List[Any] , lowercase_ : str ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('''"test requires transformers"''' ) else: test_case(self , lowercase_ ) return wrapper def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' @wraps(lowercase_ ) def wrapper(self : List[str] , lowercase_ : Union[str, Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('''"test not supported on Windows"''' ) else: test_case(self , lowercase_ ) return wrapper def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) @local class snake_case ( parameterized.TestCase ): lowerCamelCase__ = {} lowerCamelCase__ = None @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Dict = '''[...]''' __SCREAMING_SNAKE_CASE : Optional[int] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , _lowerCamelCase ) ).module_path ) __SCREAMING_SNAKE_CASE : List[str] = datasets.load.import_main_class(metric_module.__name__ , dataset=_lowerCamelCase ) # check parameters __SCREAMING_SNAKE_CASE : int = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(_lowerCamelCase , metric_module.__name__ ): with self.use_local_metrics(): try: __SCREAMING_SNAKE_CASE : Tuple = doctest.testmod(_lowerCamelCase , verbose=_lowerCamelCase , raise_on_error=_lowerCamelCase ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[Any] = '''[...]''' __SCREAMING_SNAKE_CASE : List[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , _lowerCamelCase ) ).module_path ) # run doctest with self.use_local_metrics(): __SCREAMING_SNAKE_CASE : Any = doctest.testmod(_lowerCamelCase , verbose=_lowerCamelCase , raise_on_error=_lowerCamelCase ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[Any] ): if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](_lowerCamelCase ): yield else: yield @contextmanager def SCREAMING_SNAKE_CASE_ ( self :Any ): def load_local_metric(_lowerCamelCase :Optional[Any] , *_lowerCamelCase :Dict , **_lowerCamelCase :Optional[Any] ): return load_metric(os.path.join('''metrics''' , _lowerCamelCase ) , *_lowerCamelCase , **_lowerCamelCase ) with patch('''datasets.load_metric''' ) as mock_load_metric: __SCREAMING_SNAKE_CASE : Optional[Any] = load_local_metric yield @classmethod def SCREAMING_SNAKE_CASE_ ( cls :List[str] , _lowerCamelCase :Tuple ): def wrapper(_lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = contextmanager(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('''bleurt''' ) def lowerCAmelCase_ ( lowercase_ : List[str] ): '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('''sv''' , '''''' , '''''' ) # handle pytest cli flags class snake_case ( __UpperCAmelCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): assert len(input_dict['''input_ids'''] ) == 2 return np.array([1.0_3, 1.0_4] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor: __SCREAMING_SNAKE_CASE : Dict = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('''bertscore''' ) def lowerCAmelCase_ ( lowercase_ : Optional[int] ): '''simple docstring''' import torch def bert_cos_score_idf(lowercase_ : Optional[Any] , lowercase_ : Any , *lowercase_ : int , **lowercase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(lowercase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('''bert_score.scorer.get_model''' ), patch( '''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf: __SCREAMING_SNAKE_CASE : List[str] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('''comet''' ) def lowerCAmelCase_ ( lowercase_ : Optional[int] ): '''simple docstring''' def load_from_checkpoint(lowercase_ : Tuple ): class snake_case : def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :int , *_lowerCamelCase :List[str] , **_lowerCamelCase :List[str] ): assert len(_lowerCamelCase ) == 2 __SCREAMING_SNAKE_CASE : int = [0.1_9, 0.9_2] return scores, sum(_lowerCamelCase ) / len(_lowerCamelCase ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('''comet.download_model''' ) as mock_download_model: __SCREAMING_SNAKE_CASE : str = None with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint: __SCREAMING_SNAKE_CASE : Tuple = load_from_checkpoint yield def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = load_metric(os.path.join('''metrics''' , '''seqeval''' ) ) __SCREAMING_SNAKE_CASE : List[str] = '''ERROR''' __SCREAMING_SNAKE_CASE : Union[str, Any] = F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(lowercase_ , match=re.escape(lowercase_ ) ): metric.compute(predictions=[] , references=[] , scheme=lowercase_ )
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = 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=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = 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=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": _lowerCamelCase = '''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(input('''Search: '''))) print('''Googling.....''') _lowerCamelCase = f'https://www.google.com/search?q={query}&num=100' _lowerCamelCase = requests.get( url, headers={'''User-Agent''': str(UserAgent().random)}, ) try: _lowerCamelCase = ( BeautifulSoup(res.text, '''html.parser''') .find('''div''', attrs={'''class''': '''yuRUbf'''}) .find('''a''') .get('''href''') ) except AttributeError: _lowerCamelCase = parse_qs( BeautifulSoup(res.text, '''html.parser''') .find('''div''', attrs={'''class''': '''kCrYT'''}) .find('''a''') .get('''href''') )['''url'''][0] webbrowser.open(link)
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1