code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : List[Any] = logging.get_logger(__name__) lowercase : Dict = { """xlm-mlm-en-2048""": """https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json""", """xlm-mlm-ende-1024""": """https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json""", """xlm-mlm-enfr-1024""": """https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json""", """xlm-mlm-enro-1024""": """https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json""", """xlm-mlm-tlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json""", """xlm-mlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json""", """xlm-clm-enfr-1024""": """https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json""", """xlm-clm-ende-1024""": """https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json""", """xlm-mlm-17-1280""": """https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json""", """xlm-mlm-100-1280""": """https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json""", } class __snake_case ( lowerCAmelCase ): _a : Optional[int]= "xlm" _a : List[str]= { "hidden_size": "emb_dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", "n_words": "vocab_size", # For backward compatibility } def __init__( self ,snake_case=30145 ,snake_case=2048 ,snake_case=12 ,snake_case=16 ,snake_case=0.1 ,snake_case=0.1 ,snake_case=True ,snake_case=False ,snake_case=False ,snake_case=False ,snake_case=1 ,snake_case=True ,snake_case=512 ,snake_case=2048**-0.5 ,snake_case=1e-12 ,snake_case=0.02 ,snake_case=0 ,snake_case=1 ,snake_case=2 ,snake_case=3 ,snake_case=5 ,snake_case=True ,snake_case="first" ,snake_case=True ,snake_case=None ,snake_case=True ,snake_case=0.1 ,snake_case=5 ,snake_case=5 ,snake_case=0 ,snake_case=0 ,snake_case=2 ,snake_case=0 ,**snake_case ,): '''simple docstring''' lowercase : Optional[int] = vocab_size lowercase : Any = emb_dim lowercase : Union[str, Any] = n_layers lowercase : Tuple = n_heads lowercase : Any = dropout lowercase : Optional[int] = attention_dropout lowercase : List[Any] = gelu_activation lowercase : List[str] = sinusoidal_embeddings lowercase : Dict = causal lowercase : List[Any] = asm lowercase : Optional[Any] = n_langs lowercase : Any = use_lang_emb lowercase : Optional[Any] = layer_norm_eps lowercase : Dict = bos_index lowercase : List[str] = eos_index lowercase : str = pad_index lowercase : str = unk_index lowercase : str = mask_index lowercase : str = is_encoder lowercase : Optional[int] = max_position_embeddings lowercase : Optional[Any] = embed_init_std lowercase : str = init_std lowercase : str = summary_type lowercase : Optional[Any] = summary_use_proj lowercase : int = summary_activation lowercase : List[str] = summary_proj_to_labels lowercase : Tuple = summary_first_dropout lowercase : str = start_n_top lowercase : Optional[int] = end_n_top lowercase : Optional[Any] = mask_token_id lowercase : Union[str, Any] = lang_id if "n_words" in kwargs: lowercase : Tuple = kwargs["""n_words"""] super().__init__(pad_token_id=snake_case ,bos_token_id=snake_case ,**snake_case ) class __snake_case ( lowerCAmelCase ): @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' if self.task == "multiple-choice": lowercase : List[Any] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: lowercase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
20
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _lowercase = re.compile(r'''^(?P<major>\d+)''' r'''\.(?P<minor>\d+)''' r'''\.(?P<patch>\d+)$''') @total_ordering @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: A , A , A = _str_to_version_tuple(self.version_str ) def __repr__( self : Optional[int] ) -> Dict: return F'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return self.major, self.minor, self.patch def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Tuple ) -> Union[str, Any]: if isinstance(A_ ,A_ ): return Version(A_ ) elif isinstance(A_ ,A_ ): return other raise TypeError(F'{other} (type {type(A_ )}) cannot be compared to version.' ) def __eq__( self : List[Any] ,A_ : Dict ) -> Any: try: A = self._validate_operand(A_ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : List[Any] ,A_ : Optional[int] ) -> Tuple: A = self._validate_operand(A_ ) return self.tuple < other.tuple def __hash__( self : Union[str, Any] ) -> Union[str, Any]: return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[str] ) -> List[str]: A = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.version_str def _snake_case ( snake_case__ : List[str] ): A = _VERSION_REG.match(snake_case__ ) if not res: raise ValueError(F'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(snake_case__ ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def _snake_case ( snake_case__ : str ): return ".".join(str(snake_case__ ) for v in version_tuple )
74
0
# Function to print upper half of diamond (pyramid) def UpperCamelCase_( lowerCamelCase_ ) -> List[str]: for i in range(0 , lowerCamelCase_ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def UpperCamelCase_( lowerCamelCase_ ) -> Any: for i in range(lowerCamelCase_ , 0 , -1 ): for _ in range(lowerCamelCase_ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def UpperCamelCase_( lowerCamelCase_ ) -> List[Any]: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase_ ) # upper half reverse_floyd(lowerCamelCase_ ) # lower half if __name__ == "__main__": print(r"| /\ | |- | |- |--| |\ /| |-") print(r"|/ \| |- |_ |_ |__| | \/ | |_") SCREAMING_SNAKE_CASE : Tuple = 1 while K: SCREAMING_SNAKE_CASE : Union[str, Any] = int(input("enter the number and , and see the magic : ")) print() pretty_print(user_number) SCREAMING_SNAKE_CASE : List[str] = int(input("press 0 to exit... and 1 to continue...")) print("Good Bye...")
21
"""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 _lowercase = NewType('''DataClass''', Any) _lowercase = NewType('''DataClassType''', Any) def _snake_case ( snake_case__ : Tuple ): if isinstance(snake_case__ , snake_case__ ): 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 _snake_case ( snake_case__ : list ): A = {str(snake_case__ ): choice for choice in choices} return lambda snake_case__ : str_to_choice.get(snake_case__ , snake_case__ ) def _snake_case ( *, snake_case__ : Union[str, List[str]] = None , snake_case__ : str = None , snake_case__ : Any = dataclasses.MISSING , snake_case__ : Callable[[], Any] = dataclasses.MISSING , snake_case__ : dict = None , **snake_case__ : Any , ): if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls A = {} if aliases is not None: A = aliases if help is not None: A = help return dataclasses.field(metadata=snake_case__ , default=snake_case__ , default_factory=snake_case__ , **snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Iterable[DataClassType] def __init__( self : List[str] ,A_ : Union[DataClassType, Iterable[DataClassType]] ,**A_ : Any ) -> Optional[int]: # To make the default appear when using --help if "formatter_class" not in kwargs: A = ArgumentDefaultsHelpFormatter super().__init__(**A_ ) if dataclasses.is_dataclass(A_ ): A = [dataclass_types] A = list(A_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ,A_ : dataclasses.Field ) -> Optional[Any]: A = F'--{field.name}' A = 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 ,A_ ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) A = kwargs.pop('aliases' ,[] ) if isinstance(A_ ,A_ ): A = [aliases] A = getattr(field.type ,'__origin__' ,field.type ) if origin_type is Union or (hasattr(A_ ,'UnionType' ) and isinstance(A_ ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A_ ) 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(A_ ) not in field.type.__args__: # filter `str` in Union A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] A = getattr(field.type ,'__origin__' ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) A = ( field.type.__args__[0] if isinstance(A_ ,field.type.__args__[1] ) else field.type.__args__[1] ) A = 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) A = {} if origin_type is Literal or (isinstance(field.type ,A_ ) and issubclass(field.type ,A_ )): if origin_type is Literal: A = field.type.__args__ else: A = [x.value for x in field.type] A = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: A = field.default else: A = 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 A = copy(A_ ) # Hack because type=bool in argparse does not behave as we want. A = 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. A = 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 A = default # This tells argparse we accept 0 or 1 value after --field_name A = '?' # This is the value that will get picked if we do --field_name (without value) A = True elif isclass(A_ ) and issubclass(A_ ,A_ ): A = field.type.__args__[0] A = '+' if field.default_factory is not dataclasses.MISSING: A = field.default_factory() elif field.default is dataclasses.MISSING: A = True else: A = field.type if field.default is not dataclasses.MISSING: A = field.default elif field.default_factory is not dataclasses.MISSING: A = field.default_factory() else: A = True parser.add_argument(A_ ,*A_ ,**A_ ) # 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]): A = False parser.add_argument(F'--no_{field.name}' ,action='store_false' ,dest=field.name ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : DataClassType ) -> List[Any]: if hasattr(A_ ,'_argument_group_name' ): A = self.add_argument_group(dtype._argument_group_name ) else: A = self try: A = get_type_hints(A_ ) 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(A_ ): A = '.'.join(map(A_ ,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(A_ ): if not field.init: continue A = type_hints[field.name] self._parse_dataclass_field(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Any=None ,A_ : int=False ,A_ : Any=True ,A_ : List[str]=None ,A_ : Union[str, Any]=None ,) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): A = [] if args_filename: args_files.append(Path(A_ ) ) 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 A = ArgumentParser() args_file_parser.add_argument(A_ ,type=A_ ,action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) A , A = args_file_parser.parse_known_args(args=A_ ) A = vars(A_ ).get(args_file_flag.lstrip('-' ) ,A_ ) if cmd_args_file_paths: args_files.extend([Path(A_ ) for p in cmd_args_file_paths] ) A = [] 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 A = file_args + args if args is not None else file_args + sys.argv[1:] A , A = self.parse_known_args(args=A_ ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in vars(A_ ).items() if k in keys} for k in keys: delattr(A_ ,A_ ) A = dtype(**A_ ) outputs.append(A_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A_ ) 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 _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Dict[str, Any] ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = set(args.keys() ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) A = dtype(**A_ ) outputs.append(A_ ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(A_ )}' ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: with open(Path(A_ ) ,encoding='utf-8' ) as open_json_file: A = json.loads(open_json_file.read() ) A = self.parse_dict(A_ ,allow_extra_keys=A_ ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = self.parse_dict(yaml.safe_load(Path(A_ ).read_text() ) ,allow_extra_keys=A_ ) return tuple(A_ )
74
0
'''simple docstring''' from __future__ import annotations __SCREAMING_SNAKE_CASE :Union[str, Any] = '''Muhammad Umer Farooq''' __SCREAMING_SNAKE_CASE :Optional[int] = '''MIT''' __SCREAMING_SNAKE_CASE :Any = '''1.0.0''' __SCREAMING_SNAKE_CASE :Union[str, Any] = '''Muhammad Umer Farooq''' __SCREAMING_SNAKE_CASE :Optional[int] = '''contact@muhammadumerfarooq.me''' __SCREAMING_SNAKE_CASE :Any = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class A_ ( lowerCAmelCase_ ): def __init__( self : Tuple , snake_case_ : str ): super().__init__() _UpperCAmelCase = [] _UpperCAmelCase = domain def lowercase ( self : List[Any] , snake_case_ : str , snake_case_ : list[tuple[str, str | None]] ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: _UpperCAmelCase = parse.urljoin(self.domain , snake_case_ ) self.urls.append(snake_case_ ) def UpperCAmelCase_ ( __lowercase : str ) -> str: '''simple docstring''' return ".".join(get_sub_domain_name(__lowercase ).split("." )[-2:] ) def UpperCAmelCase_ ( __lowercase : str ) -> str: '''simple docstring''' return parse.urlparse(__lowercase ).netloc def UpperCAmelCase_ ( __lowercase : str = "https://github.com" ) -> list[str]: '''simple docstring''' _UpperCAmelCase = get_domain_name(__lowercase ) # Initialize the parser _UpperCAmelCase = Parser(__lowercase ) try: # Open URL _UpperCAmelCase = requests.get(__lowercase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through _UpperCAmelCase = set() for link in parser.urls: # open URL. # read = requests.get(link) try: _UpperCAmelCase = requests.get(__lowercase ) # Get the valid email. _UpperCAmelCase = re.findall("[a-zA-Z0-9]+@" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__lowercase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__lowercase ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE :str = emails_from_url('''https://github.com''') print(F"{len(emails)} emails found:") print('''\n'''.join(sorted(emails)))
22
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Dict ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : int ): # 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(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Optional[int] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
74
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__: List[Any] = logging.get_logger(__name__) UpperCamelCase__: List[Any] = { "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json", } class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = """lxmert""" lowerCamelCase__ = {} def __init__( self : Tuple , __snake_case : int=30522 , __snake_case : Union[str, Any]=768 , __snake_case : List[str]=12 , __snake_case : Any=9500 , __snake_case : int=1600 , __snake_case : Any=400 , __snake_case : Dict=3072 , __snake_case : int="gelu" , __snake_case : List[Any]=0.1 , __snake_case : Any=0.1 , __snake_case : Optional[Any]=512 , __snake_case : str=2 , __snake_case : Optional[Any]=0.02 , __snake_case : Optional[Any]=1E-12 , __snake_case : Dict=9 , __snake_case : Any=5 , __snake_case : int=5 , __snake_case : Tuple=2048 , __snake_case : Union[str, Any]=4 , __snake_case : Optional[Any]=6.67 , __snake_case : Optional[int]=True , __snake_case : str=True , __snake_case : List[Any]=True , __snake_case : List[Any]=True , __snake_case : int=True , __snake_case : Dict=True , __snake_case : int=True , **__snake_case : int , ) -> Optional[int]: UpperCAmelCase : List[str] = vocab_size UpperCAmelCase : Optional[Any] = hidden_size UpperCAmelCase : Tuple = num_attention_heads UpperCAmelCase : List[str] = hidden_act UpperCAmelCase : Optional[Any] = intermediate_size UpperCAmelCase : Tuple = hidden_dropout_prob UpperCAmelCase : Dict = attention_probs_dropout_prob UpperCAmelCase : Tuple = max_position_embeddings UpperCAmelCase : str = type_vocab_size UpperCAmelCase : Dict = initializer_range UpperCAmelCase : List[Any] = layer_norm_eps UpperCAmelCase : List[Any] = num_qa_labels UpperCAmelCase : Optional[Any] = num_object_labels UpperCAmelCase : Optional[int] = num_attr_labels UpperCAmelCase : List[Any] = l_layers UpperCAmelCase : Optional[Any] = x_layers UpperCAmelCase : Optional[Any] = r_layers UpperCAmelCase : Union[str, Any] = visual_feat_dim UpperCAmelCase : Dict = visual_pos_dim UpperCAmelCase : Optional[int] = visual_loss_normalizer UpperCAmelCase : Any = task_matched UpperCAmelCase : List[Any] = task_mask_lm UpperCAmelCase : List[str] = task_obj_predict UpperCAmelCase : List[Any] = task_qa UpperCAmelCase : Any = visual_obj_loss UpperCAmelCase : Any = visual_attr_loss UpperCAmelCase : Dict = visual_feat_loss UpperCAmelCase : Union[str, Any] = {'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers} super().__init__(**__snake_case )
23
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
0
# limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( 'pipelines_utils', '0.22.0', 'Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.', standard_warn=False, stacklevel=3, )
24
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase = logging.get_logger(__name__) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : int ,**A_ : Any ) -> Any: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A = deprecated_arg[3:] A = not kwargs.pop(A_ ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) A = kwargs.pop('tpu_name' ,self.tpu_name ) A = kwargs.pop('device_idx' ,self.device_idx ) A = kwargs.pop('eager_mode' ,self.eager_mode ) A = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**A_ ) _lowerCamelCase: str = field( default=_lowercase , metadata={'''help''': '''Name of TPU'''} , ) _lowerCamelCase: int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) _lowerCamelCase: bool = field(default=_lowercase , metadata={'''help''': '''Benchmark models in eager model.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) A = None if self.tpu: try: if self.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: A = None return tpu @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) A = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) A = tf.distribute.OneDeviceStrategy(device=F'/gpu:{self.device_idx}' ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU A = tf.distribute.OneDeviceStrategy(device=F'/cpu:{self.device_idx}' ) return strategy @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def _SCREAMING_SNAKE_CASE ( self : int ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _SCREAMING_SNAKE_CASE ( self : str ) -> bool: return self.n_gpu > 0
74
0
"""simple docstring""" from __future__ import annotations from typing import Any def lowercase_ ( _snake_case ): if not postfix_notation: return 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""+""", """-""", """*""", """/"""} SCREAMING_SNAKE_CASE__ : list[Any] = [] for token in postfix_notation: if token in operations: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(_snake_case ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
25
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowercase = logging.get_logger(__name__) _lowercase = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''dpt''' def __init__( self : str ,A_ : Tuple=768 ,A_ : int=12 ,A_ : Optional[int]=12 ,A_ : Optional[int]=3072 ,A_ : List[str]="gelu" ,A_ : str=0.0 ,A_ : int=0.0 ,A_ : str=0.02 ,A_ : str=1e-12 ,A_ : str=384 ,A_ : Dict=16 ,A_ : Union[str, Any]=3 ,A_ : Dict=False ,A_ : Any=True ,A_ : Optional[int]=[2, 5, 8, 11] ,A_ : Optional[Any]="project" ,A_ : Tuple=[4, 2, 1, 0.5] ,A_ : int=[96, 192, 384, 768] ,A_ : int=256 ,A_ : str=-1 ,A_ : Optional[int]=False ,A_ : Optional[int]=True ,A_ : Union[str, Any]=0.4 ,A_ : Union[str, Any]=255 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=[1, 1024, 24, 24] ,A_ : List[str]=[0, 1] ,A_ : List[Any]=None ,**A_ : Tuple ,) -> Union[str, Any]: super().__init__(**A_ ) A = hidden_size A = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): logger.info('Initializing the config with a `BiT` backbone.' ) A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): A = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) A = backbone_featmap_shape A = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: A = None A = None A = [] A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) A = readout_type A = reassemble_factors A = neck_hidden_sizes A = fusion_hidden_size A = head_in_index A = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) A = use_auxiliary_head A = auxiliary_loss_weight A = semantic_loss_ignore_index A = semantic_classifier_dropout def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: A = self.backbone_config.to_dict() A = self.__class__.model_type return output
74
0
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) _snake_case = [ ["attention", "attn"], ["encoder_attention", "encoder_attn"], ["q_lin", "q_proj"], ["k_lin", "k_proj"], ["v_lin", "v_proj"], ["out_lin", "out_proj"], ["norm_embeddings", "layernorm_embedding"], ["position_embeddings", "embed_positions"], ["embeddings", "embed_tokens"], ["ffn.lin", "fc"], ] def lowerCAmelCase_ ( snake_case_ ): if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: _A : str = k.replace(snake_case_,snake_case_ ) if k.startswith("""encoder""" ): _A : Optional[Any] = k.replace(""".attn""",""".self_attn""" ) _A : Dict = k.replace("""norm1""","""self_attn_layer_norm""" ) _A : Optional[Any] = k.replace("""norm2""","""final_layer_norm""" ) elif k.startswith("""decoder""" ): _A : str = k.replace("""norm1""","""self_attn_layer_norm""" ) _A : Any = k.replace("""norm2""","""encoder_attn_layer_norm""" ) _A : Optional[int] = k.replace("""norm3""","""final_layer_norm""" ) return k def lowerCAmelCase_ ( snake_case_ ): _A : List[Any] = [ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: _A : str = sd.pop(snake_case_ ) _A : Optional[int] = k.replace("""layernorm_embedding""","""layer_norm""" ) assert new_k not in sd _A : Optional[int] = v _snake_case = ["START"] @torch.no_grad() def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Tuple = torch.load(snake_case_,map_location="""cpu""" ) _A : List[Any] = model["""model"""] _A : Optional[Any] = BlenderbotConfig.from_json_file(snake_case_ ) _A : List[str] = BlenderbotForConditionalGeneration(snake_case_ ) _A : Tuple = m.model.state_dict().keys() _A : Any = [] _A : Dict = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue _A : Optional[int] = rename_state_dict_key(snake_case_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: _A : Dict = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(snake_case_ ) m.model.load_state_dict(snake_case_,strict=snake_case_ ) m.half() m.save_pretrained(snake_case_ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin") parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.") parser.add_argument( "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use" ) _snake_case = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
26
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
0
'''simple docstring''' import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "char" A_ = "bpe" A_ = "wp" __lowercase : Dict = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __UpperCamelCase ( lowerCAmelCase_ ): A_ = ["image_processor", "char_tokenizer"] A_ = "ViTImageProcessor" A_ = "MgpstrTokenizer" def __init__( self , __a=None , __a=None , **__a ): '''simple docstring''' __a : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __a , ) __a : Any = kwargs.pop('feature_extractor' ) __a : Union[str, Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __a : Any = tokenizer __a : int = AutoTokenizer.from_pretrained('gpt2' ) __a : List[Any] = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(__a , __a ) def __call__( self , __a=None , __a=None , __a=None , **__a ): '''simple docstring''' if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __a : List[str] = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None: __a : Optional[int] = self.char_tokenizer(__a , return_tensors=__a , **__a ) if text is None: return inputs elif images is None: return encodings else: __a : Dict = encodings['input_ids'] return inputs def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a , __a , __a : Optional[int] = sequences __a : List[Any] = char_preds.size(0 ) __a , __a : int = self._decode_helper(__a , 'char' ) __a , __a : List[str] = self._decode_helper(__a , 'bpe' ) __a , __a : Dict = self._decode_helper(__a , 'wp' ) __a : Dict = [] __a : Optional[Any] = [] for i in range(__a ): __a : Dict = [char_scores[i], bpe_scores[i], wp_scores[i]] __a : Union[str, Any] = [char_strs[i], bpe_strs[i], wp_strs[i]] __a : int = scores.index(max(__a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __a : Union[str, Any] = {} __a : Optional[Any] = final_strs __a : List[Any] = final_scores __a : Tuple = char_strs __a : Optional[int] = bpe_strs __a : Optional[Any] = wp_strs return out def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' if format == DecodeType.CHARACTER: __a : str = self.char_decode __a : Tuple = 1 __a : Optional[int] = '[s]' elif format == DecodeType.BPE: __a : str = self.bpe_decode __a : Optional[int] = 2 __a : Tuple = '#' elif format == DecodeType.WORDPIECE: __a : List[str] = self.wp_decode __a : str = 102 __a : Any = '[SEP]' else: raise ValueError(f"""Format {format} is not supported.""" ) __a , __a : Tuple = [], [] __a : Union[str, Any] = pred_logits.size(0 ) __a : Union[str, Any] = pred_logits.size(1 ) __a , __a : Optional[Any] = pred_logits.topk(1 , dim=-1 , largest=__a , sorted=__a ) __a : str = preds_index.view(-1 , __a )[:, 1:] __a : Optional[int] = decoder(__a ) __a , __a : Tuple = torch.nn.functional.softmax(__a , dim=2 ).max(dim=2 ) __a : List[str] = preds_max_prob[:, 1:] for index in range(__a ): __a : int = preds_str[index].find(__a ) __a : Dict = preds_str[index][:pred_eos] __a : List[str] = preds_index[index].cpu().tolist() __a : List[Any] = pred_index.index(__a ) if eos_token in pred_index else -1 __a : Optional[int] = preds_max_prob[index][: pred_eos_index + 1] __a : List[str] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__a ) conf_scores.append(__a ) return dec_strs, conf_scores def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Union[str, Any] = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(__a )] return decode_strs def __UpperCAmelCase ( self , __a ): '''simple docstring''' return self.bpe_tokenizer.batch_decode(__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : str = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(__a )] return decode_strs
27
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ,A_ : int ) -> Union[str, Any]: A = n A = [None] * self.n A = 0 # index of the first element A = 0 A = 0 def __len__( self : int ) -> int: return self.size def _SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.size == 0 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: return False if self.is_empty() else self.array[self.front] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ) -> int: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A = data A = (self.rear + 1) % self.n self.size += 1 return self def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) A = self.array[self.front] A = None A = (self.front + 1) % self.n self.size -= 1 return temp
74
0
'''simple docstring''' import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def __lowerCamelCase ( A__ , A__ , A__ , A__="attention" ) -> Tuple: """simple docstring""" UpperCamelCase = params[F"""{prefix}/layers_{i}/{layer_name}/key/kernel"""] UpperCamelCase = params[F"""{prefix}/layers_{i}/{layer_name}/out/kernel"""] UpperCamelCase = params[F"""{prefix}/layers_{i}/{layer_name}/query/kernel"""] UpperCamelCase = params[F"""{prefix}/layers_{i}/{layer_name}/value/kernel"""] return k, o, q, v def __lowerCamelCase ( A__ , A__ , A__ , A__=False ) -> Optional[int]: """simple docstring""" if split_mlp_wi: UpperCamelCase = params[F"""{prefix}/layers_{i}/mlp/wi_0/kernel"""] UpperCamelCase = params[F"""{prefix}/layers_{i}/mlp/wi_1/kernel"""] UpperCamelCase = (wi_a, wi_a) else: UpperCamelCase = params[F"""{prefix}/layers_{i}/mlp/wi/kernel"""] UpperCamelCase = params[F"""{prefix}/layers_{i}/mlp/wo/kernel"""] return wi, wo def __lowerCamelCase ( A__ , A__ , A__ , A__ ) -> Tuple: """simple docstring""" return params[F"""{prefix}/layers_{i}/{layer_name}/scale"""] def __lowerCamelCase ( A__ , *, A__ , A__ ) -> Tuple: """simple docstring""" UpperCamelCase = traverse_util.flatten_dict(variables['target'] ) UpperCamelCase = {'/'.join(A__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase = 'encoder/layers_0/mlp/wi_0/kernel' in old print('Split MLP:' , A__ ) UpperCamelCase = collections.OrderedDict() # Shared embeddings. UpperCamelCase = old['token_embedder/embedding'] # Encoder. for i in range(A__ ): # Block i, layer 0 (Self Attention). UpperCamelCase = tax_layer_norm_lookup(A__ , A__ , 'encoder' , 'pre_attention_layer_norm' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = tax_attention_lookup(A__ , A__ , 'encoder' , 'attention' ) UpperCamelCase = layer_norm UpperCamelCase = k.T UpperCamelCase = o.T UpperCamelCase = q.T UpperCamelCase = v.T # Block i, layer 1 (MLP). UpperCamelCase = tax_layer_norm_lookup(A__ , A__ , 'encoder' , 'pre_mlp_layer_norm' ) UpperCamelCase , UpperCamelCase = tax_mlp_lookup(A__ , A__ , 'encoder' , A__ ) UpperCamelCase = layer_norm if split_mlp_wi: UpperCamelCase = wi[0].T UpperCamelCase = wi[1].T else: UpperCamelCase = wi.T UpperCamelCase = wo.T UpperCamelCase = old[ 'encoder/relpos_bias/rel_embedding' ].T UpperCamelCase = old['encoder/encoder_norm/scale'] if not is_encoder_only: # Decoder. for i in range(A__ ): # Block i, layer 0 (Self Attention). UpperCamelCase = tax_layer_norm_lookup(A__ , A__ , 'decoder' , 'pre_self_attention_layer_norm' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = tax_attention_lookup(A__ , A__ , 'decoder' , 'self_attention' ) UpperCamelCase = layer_norm UpperCamelCase = k.T UpperCamelCase = o.T UpperCamelCase = q.T UpperCamelCase = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase = tax_layer_norm_lookup(A__ , A__ , 'decoder' , 'pre_cross_attention_layer_norm' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = tax_attention_lookup(A__ , A__ , 'decoder' , 'encoder_decoder_attention' ) UpperCamelCase = layer_norm UpperCamelCase = k.T UpperCamelCase = o.T UpperCamelCase = q.T UpperCamelCase = v.T # Block i, layer 2 (MLP). UpperCamelCase = tax_layer_norm_lookup(A__ , A__ , 'decoder' , 'pre_mlp_layer_norm' ) UpperCamelCase , UpperCamelCase = tax_mlp_lookup(A__ , A__ , 'decoder' , A__ ) UpperCamelCase = layer_norm if split_mlp_wi: UpperCamelCase = wi[0].T UpperCamelCase = wi[1].T else: UpperCamelCase = wi.T UpperCamelCase = wo.T UpperCamelCase = old['decoder/decoder_norm/scale'] UpperCamelCase = old[ 'decoder/relpos_bias/rel_embedding' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase = old['decoder/logits_dense/kernel'].T return new def __lowerCamelCase ( A__ , A__ ) -> str: """simple docstring""" UpperCamelCase = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) UpperCamelCase = state_dict['shared.weight'] return state_dict def __lowerCamelCase ( A__ , A__ , A__ , A__ ) -> str: """simple docstring""" UpperCamelCase = checkpoints.load_tax_checkpoint(A__ ) UpperCamelCase = convert_tax_to_pytorch(A__ , num_layers=config.num_layers , is_encoder_only=A__ ) UpperCamelCase = make_state_dict(A__ , A__ ) model.load_state_dict(A__ , strict=A__ ) def __lowerCamelCase ( A__ , A__ , A__ , A__ = False ) -> Tuple: """simple docstring""" UpperCamelCase = TaConfig.from_json_file(A__ ) print(F"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase = TaEncoderModel(A__ ) else: UpperCamelCase = TaForConditionalGeneration(A__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(A__ , A__ , A__ , A__ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(A__ ) # Verify that we can load the checkpoint. model.from_pretrained(A__ ) print('Done' ) if __name__ == "__main__": _lowerCamelCase : int = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) _lowerCamelCase : Union[str, Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
28
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,*A_ : List[str] ,**A_ : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' ,A_ ,) super().__init__(*A_ ,**A_ )
74
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'studio-ousia/luke-base': 'https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json', 'studio-ousia/luke-large': 'https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json', } class lowerCamelCase (_snake_case ): '''simple docstring''' _snake_case : int = '''luke''' def __init__( self , _UpperCamelCase=5_0_2_6_7 , _UpperCamelCase=5_0_0_0_0_0 , _UpperCamelCase=7_6_8 , _UpperCamelCase=2_5_6 , _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=True , _UpperCamelCase=None , _UpperCamelCase=1 , _UpperCamelCase=0 , _UpperCamelCase=2 , **_UpperCamelCase , ) -> str: super().__init__(pad_token_id=_UpperCamelCase , bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase , **_UpperCamelCase ) UpperCAmelCase_ : Any = vocab_size UpperCAmelCase_ : Optional[int] = entity_vocab_size UpperCAmelCase_ : Optional[int] = hidden_size UpperCAmelCase_ : Optional[int] = entity_emb_size UpperCAmelCase_ : Optional[int] = num_hidden_layers UpperCAmelCase_ : int = num_attention_heads UpperCAmelCase_ : str = hidden_act UpperCAmelCase_ : Any = intermediate_size UpperCAmelCase_ : Any = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : List[str] = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : Dict = initializer_range UpperCAmelCase_ : Optional[Any] = layer_norm_eps UpperCAmelCase_ : Optional[int] = use_entity_aware_attention UpperCAmelCase_ : Optional[int] = classifier_dropout
29
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''gpt_bigcode''' _lowerCamelCase: List[Any] = ['''past_key_values'''] _lowerCamelCase: int = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Optional[int] ,A_ : Dict=5_0257 ,A_ : Union[str, Any]=1024 ,A_ : str=768 ,A_ : Any=12 ,A_ : Any=12 ,A_ : Optional[int]=None ,A_ : Any="gelu_pytorch_tanh" ,A_ : List[str]=0.1 ,A_ : Optional[int]=0.1 ,A_ : List[str]=0.1 ,A_ : Tuple=1e-5 ,A_ : Optional[int]=0.02 ,A_ : List[str]=True ,A_ : Optional[Any]=True ,A_ : List[Any]=5_0256 ,A_ : Union[str, Any]=5_0256 ,A_ : int=True ,A_ : Optional[Any]=True ,A_ : Dict=True ,**A_ : Union[str, Any] ,) -> Union[str, Any]: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = scale_attn_weights A = use_cache A = attention_softmax_in_fpaa A = scale_attention_softmax_in_fpaa A = multi_query A = bos_token_id A = eos_token_id super().__init__(bos_token_id=A_ ,eos_token_id=A_ ,**A_ )
74
0
import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __a = logging.get_logger(__name__) __a = { 'vocab_file': 'vocab.txt', 'merges_file': 'bpe.codes', } __a = { 'vocab_file': { 'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt', 'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt', }, 'merges_file': { 'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes', 'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes', }, } __a = { 'vinai/phobert-base': 2_5_6, 'vinai/phobert-large': 2_5_6, } def a ( snake_case__: List[str] ): '''simple docstring''' lowercase_ = set() lowercase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowercase_ = char lowercase_ = set(snake_case__ ) return pairs class lowercase__( UpperCAmelCase ): """simple docstring""" a :Optional[Any] = VOCAB_FILES_NAMES a :List[str] = PRETRAINED_VOCAB_FILES_MAP a :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any]="<s>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="</s>" , SCREAMING_SNAKE_CASE_ : List[Any]="</s>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="<s>" , SCREAMING_SNAKE_CASE_ : List[str]="<unk>" , SCREAMING_SNAKE_CASE_ : List[Any]="<pad>" , SCREAMING_SNAKE_CASE_ : List[Any]="<mask>" , **SCREAMING_SNAKE_CASE_ : Optional[Any] , ) -> Union[str, Any]: super().__init__( bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowercase_ = vocab_file lowercase_ = merges_file lowercase_ = {} lowercase_ = 0 lowercase_ = 1 lowercase_ = 2 lowercase_ = 3 self.add_from_file(SCREAMING_SNAKE_CASE_ ) lowercase_ = {v: k for k, v in self.encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='''utf-8''' ) as merges_handle: lowercase_ = merges_handle.read().split('''\n''' )[:-1] lowercase_ = [tuple(merge.split()[:-1] ) for merge in merges] lowercase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowercase_ = {} def _lowercase ( self : Any , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowercase_ = [self.cls_token_id] lowercase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE_ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def _lowercase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: lowercase_ = [self.sep_token_id] lowercase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _lowercase ( self : Any ) -> Any: return len(self.encoder ) def _lowercase ( self : Any ) -> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : Any ) -> Any: if token in self.cache: return self.cache[token] lowercase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowercase_ = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) lowercase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowercase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break lowercase_ , lowercase_ = bigram lowercase_ = [] lowercase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowercase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowercase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowercase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowercase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowercase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowercase_ = '''@@ '''.join(SCREAMING_SNAKE_CASE_ ) lowercase_ = word[:-4] lowercase_ = word return word def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict ) -> int: lowercase_ = [] lowercase_ = re.findall(R'''\S+\n?''' , SCREAMING_SNAKE_CASE_ ) for token in words: split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE_ ).split(''' ''' ) ) ) return split_tokens def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Union[str, Any]: return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> List[Any]: return self.decoder.get(SCREAMING_SNAKE_CASE_ , self.unk_token ) def _lowercase ( self : Any , SCREAMING_SNAKE_CASE_ : Any ) -> Tuple: lowercase_ = ''' '''.join(SCREAMING_SNAKE_CASE_ ).replace('''@@ ''' , '''''' ).strip() return out_string def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ ) if os.path.abspath(self.merges_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ): copyfile(self.merges_file , SCREAMING_SNAKE_CASE_ ) return out_vocab_file, out_merge_file def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Dict: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): try: with open(SCREAMING_SNAKE_CASE_ , '''r''' , encoding='''utf-8''' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE_ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(f'''Incorrect encoding detected in {f}, please rebuild the dataset''' ) return lowercase_ = f.readlines() for lineTmp in lines: lowercase_ = lineTmp.strip() lowercase_ = line.rfind(''' ''' ) if idx == -1: raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt>\'''' ) lowercase_ = line[:idx] lowercase_ = len(self.encoder )
30
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class lowerCamelCase_ (unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[int] ): _UpperCAmelCase : Dict = tempfile.mkdtemp() _UpperCAmelCase : Any = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _UpperCAmelCase : 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] ) ) _UpperCAmelCase : int = { "do_resize": True, "size": 20, "do_center_crop": True, "crop_size": 18, "do_normalize": True, "image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073], "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711], } _UpperCAmelCase : List[Any] = os.path.join(self.tmpdirname , A ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(A , A ) def _A ( self : Dict , **A : List[Any] ): return BertTokenizer.from_pretrained(self.tmpdirname , **A ) def _A ( self : List[str] , **A : Tuple ): return BertTokenizerFast.from_pretrained(self.tmpdirname , **A ) def _A ( self : Dict , **A : Dict ): return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **A ) def _A ( self : str ): shutil.rmtree(self.tmpdirname ) def _A ( self : Union[str, Any] ): _UpperCAmelCase : Any = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCAmelCase : Any = [Image.fromarray(np.moveaxis(A , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self : List[str] ): _UpperCAmelCase : Optional[Any] = self.get_tokenizer() _UpperCAmelCase : Optional[int] = self.get_rust_tokenizer() _UpperCAmelCase : Union[str, Any] = self.get_image_processor() _UpperCAmelCase : Optional[Any] = AlignProcessor(tokenizer=A , image_processor=A ) processor_slow.save_pretrained(self.tmpdirname ) _UpperCAmelCase : str = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=A ) _UpperCAmelCase : List[Any] = AlignProcessor(tokenizer=A , image_processor=A ) processor_fast.save_pretrained(self.tmpdirname ) _UpperCAmelCase : Optional[Any] = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , A ) self.assertIsInstance(processor_fast.tokenizer , A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , A ) self.assertIsInstance(processor_fast.image_processor , A ) def _A ( self : List[Any] ): _UpperCAmelCase : Tuple = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCAmelCase : Dict = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) _UpperCAmelCase : Optional[int] = self.get_image_processor(do_normalize=A , padding_value=1.0 ) _UpperCAmelCase : Optional[int] = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A ) def _A ( self : List[str] ): _UpperCAmelCase : List[str] = self.get_image_processor() _UpperCAmelCase : Any = self.get_tokenizer() _UpperCAmelCase : str = AlignProcessor(tokenizer=A , image_processor=A ) _UpperCAmelCase : Optional[int] = self.prepare_image_inputs() _UpperCAmelCase : Dict = image_processor(A , return_tensors="np" ) _UpperCAmelCase : Optional[Any] = processor(images=A , return_tensors="np" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _A ( self : Tuple ): _UpperCAmelCase : List[Any] = self.get_image_processor() _UpperCAmelCase : Union[str, Any] = self.get_tokenizer() _UpperCAmelCase : Optional[int] = AlignProcessor(tokenizer=A , image_processor=A ) _UpperCAmelCase : List[str] = "lower newer" _UpperCAmelCase : Any = processor(text=A ) _UpperCAmelCase : Optional[Any] = tokenizer(A , padding="max_length" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _A ( self : int ): _UpperCAmelCase : Optional[int] = self.get_image_processor() _UpperCAmelCase : Any = self.get_tokenizer() _UpperCAmelCase : str = AlignProcessor(tokenizer=A , image_processor=A ) _UpperCAmelCase : Tuple = "lower newer" _UpperCAmelCase : Union[str, Any] = self.prepare_image_inputs() _UpperCAmelCase : Dict = processor(text=A , images=A ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(A ): processor() def _A ( self : int ): _UpperCAmelCase : Optional[int] = self.get_image_processor() _UpperCAmelCase : Tuple = self.get_tokenizer() _UpperCAmelCase : str = AlignProcessor(tokenizer=A , image_processor=A ) _UpperCAmelCase : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCAmelCase : str = processor.batch_decode(A ) _UpperCAmelCase : Optional[Any] = tokenizer.batch_decode(A ) self.assertListEqual(A , A ) def _A ( self : Tuple ): _UpperCAmelCase : int = self.get_image_processor() _UpperCAmelCase : Tuple = self.get_tokenizer() _UpperCAmelCase : Optional[Any] = AlignProcessor(tokenizer=A , image_processor=A ) _UpperCAmelCase : List[Any] = "lower newer" _UpperCAmelCase : int = self.prepare_image_inputs() _UpperCAmelCase : Optional[int] = processor(text=A , images=A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
31
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def SCREAMING_SNAKE_CASE_ ( __A : list , __A : list , __A : list , __A : list , __A : list ) -> float: """simple docstring""" a_ : Dict = np.array([[1, item, train_mtch[i]] for i, item in enumerate(__A )] ) a_ : Union[str, Any] = np.array(__A ) a_ : Dict = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , __A ) ) , x.transpose() ) , __A ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def SCREAMING_SNAKE_CASE_ ( __A : list , __A : list , __A : list ) -> float: """simple docstring""" a_ : Optional[Any] = (1, 2, 1) a_ : List[Any] = (1, 1, 0, 7) a_ : Optional[int] = SARIMAX( __A , exog=__A , order=__A , seasonal_order=__A ) a_ : Union[str, Any] = model.fit(disp=__A , maxiter=6_00 , method='nm' ) a_ : int = model_fit.predict(1 , len(__A ) , exog=[test_match] ) return result[0] def SCREAMING_SNAKE_CASE_ ( __A : list , __A : list , __A : list ) -> float: """simple docstring""" a_ : List[str] = SVR(kernel='rbf' , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(__A , __A ) a_ : Union[str, Any] = regressor.predict(__A ) return y_pred[0] def SCREAMING_SNAKE_CASE_ ( __A : list ) -> float: """simple docstring""" train_user.sort() a_ : str = np.percentile(__A , 25 ) a_ : Optional[Any] = np.percentile(__A , 75 ) a_ : Any = qa - qa a_ : Union[str, Any] = qa - (iqr * 0.1) return low_lim def SCREAMING_SNAKE_CASE_ ( __A : list , __A : float ) -> bool: """simple docstring""" a_ : Dict = 0 a_ : Optional[int] = 0 for i in list_vote: if i > actual_result: a_ : str = not_safe + 1 else: if abs(abs(__A ) - abs(__A ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) UpperCAmelCase_ : List[str] = [[1_8231, 0.0, 1], [2_2621, 1.0, 2], [1_5675, 0.0, 3], [2_3583, 1.0, 4]] UpperCAmelCase_ : Dict = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) UpperCAmelCase_ : int = Normalizer().fit_transform(data_input_df.values) # split data UpperCAmelCase_ : List[str] = normalize_df[:, 2].tolist() UpperCAmelCase_ : Dict = normalize_df[:, 0].tolist() UpperCAmelCase_ : List[Any] = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) UpperCAmelCase_ : int = normalize_df[:, [1, 2]].tolist() UpperCAmelCase_ : List[str] = x[: len(x) - 1] UpperCAmelCase_ : Any = x[len(x) - 1 :] # for linear regression & sarimax UpperCAmelCase_ : Optional[int] = total_date[: len(total_date) - 1] UpperCAmelCase_ : str = total_user[: len(total_user) - 1] UpperCAmelCase_ : List[Any] = total_match[: len(total_match) - 1] UpperCAmelCase_ : Optional[int] = total_date[len(total_date) - 1 :] UpperCAmelCase_ : Any = total_user[len(total_user) - 1 :] UpperCAmelCase_ : str = total_match[len(total_match) - 1 :] # voting system with forecasting UpperCAmelCase_ : Optional[Any] = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data UpperCAmelCase_ : Optional[Any] = '' if data_safety_checker(res_vote, tst_user) else 'not ' print('Today\'s data is {not_str}safe.')
32
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
0
"""simple docstring""" import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''): __A : List[str] = True from torch.cuda.amp import autocast __A : str = logging.getLogger(__name__) @dataclass class _UpperCAmelCase : SCREAMING_SNAKE_CASE_ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) SCREAMING_SNAKE_CASE_ : Optional[str] = field( default=_A , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) SCREAMING_SNAKE_CASE_ : Optional[bool] = field( default=_A , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) SCREAMING_SNAKE_CASE_ : Optional[bool] = field( default=_A , metadata={"help": "Whether to log verbose messages or not."} , ) SCREAMING_SNAKE_CASE_ : Optional[float] = field( default=2.0 , metadata={"help": "Maximum temperature for gumbel softmax."} ) SCREAMING_SNAKE_CASE_ : Optional[float] = field( default=0.5 , metadata={"help": "Minimum temperature for gumbel softmax."} ) SCREAMING_SNAKE_CASE_ : Optional[float] = field( default=0.999_995 , metadata={"help": "Decay of gumbel temperature during training."} ) def lowercase ( __snake_case : ModelArguments , __snake_case : TrainingArguments ): logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) lowercase_ : int = logging.WARNING if model_args.verbose_logging: lowercase_ : Any = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): lowercase_ : Tuple = logging.INFO logger.setLevel(__snake_case ) @dataclass class _UpperCAmelCase : SCREAMING_SNAKE_CASE_ : str = field( default=_A , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) SCREAMING_SNAKE_CASE_ : Optional[str] = field( default=_A , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) SCREAMING_SNAKE_CASE_ : Optional[str] = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) SCREAMING_SNAKE_CASE_ : Optional[str] = field( default="validation" , metadata={ "help": ( "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) SCREAMING_SNAKE_CASE_ : Optional[str] = field( default="file" , metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"} , ) SCREAMING_SNAKE_CASE_ : bool = field( default=_A , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) SCREAMING_SNAKE_CASE_ : Optional[int] = field( default=1 , metadata={ "help": "The percentage of the train set used as validation set in case there's no validation split" } , ) SCREAMING_SNAKE_CASE_ : Optional[int] = field( default=_A , metadata={"help": "The number of processes to use for the preprocessing."} , ) SCREAMING_SNAKE_CASE_ : Optional[float] = field( default=20.0 , metadata={"help": "Filter audio files that are longer than `max_duration_in_seconds` seconds"} ) @dataclass class _UpperCAmelCase : SCREAMING_SNAKE_CASE_ : WavaVecaForPreTraining SCREAMING_SNAKE_CASE_ : WavaVecaFeatureExtractor SCREAMING_SNAKE_CASE_ : Union[bool, str] = "longest" SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Optional[int] = None def __call__( self : Union[str, Any] , A : List[Dict[str, Union[List[int], torch.Tensor]]] ) -> Dict[str, torch.Tensor]: # reformat list to dict and set to pytorch format lowercase_ : List[str] = self.feature_extractor.pad( A , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) lowercase_ : Tuple = self.model._get_feat_extract_output_lengths(batch['''input_values'''].shape[-1] ) lowercase_ : Union[str, Any] = batch['''input_values'''].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula lowercase_ : Any = self.model._get_feat_extract_output_lengths(batch['''attention_mask'''].sum(-1 ) ).to( torch.long ) lowercase_ : str = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch['''input_values'''].device ) # these two operations makes sure that all values # before the output lengths indices are attended to lowercase_ : Optional[Any] = 1 lowercase_ : Tuple = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices lowercase_ : Union[str, Any] = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=A , min_masks=2 , ) return batch class _UpperCAmelCase ( _A ): def __init__( self : Optional[Any] , *A : Dict , A : Any=1 , A : Dict=0 , A : Optional[int]=1.0 , **A : str ) -> Tuple: super().__init__(*A , **A ) lowercase_ : Any = 0 lowercase_ : Tuple = max_gumbel_temp lowercase_ : int = min_gumbel_temp lowercase_ : Optional[Any] = gumbel_temp_decay def A ( self : str , A : nn.Module , A : Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor: model.train() lowercase_ : Any = self._prepare_inputs(A ) if self.use_amp: with autocast(): lowercase_ : Union[str, Any] = self.compute_loss(A , A ) else: lowercase_ : str = self.compute_loss(A , A ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": lowercase_ : Optional[int] = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowercase_ : List[Any] = loss.sum() / (inputs['''mask_time_indices''']).sum() else: raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' ) if self.args.gradient_accumulation_steps > 1: lowercase_ : int = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(A ).backward() elif self.use_apex: with amp.scale_loss(A , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(A ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def lowercase ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowercase_ , lowercase_ , lowercase_ : Optional[Any] = parser.parse_args_into_dataclasses() configure_logger(__snake_case , __snake_case ) # Downloading and loading a dataset from the hub. lowercase_ : Union[str, Any] = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" lowercase_ : Optional[int] = DatasetDict() lowercase_ : int = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[:{data_args.validation_split_percentage}%]''' , cache_dir=model_args.cache_dir , ) lowercase_ : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[{data_args.validation_split_percentage}%:]''' , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" lowercase_ : Dict = DatasetDict() lowercase_ : List[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split='''validation''' , cache_dir=model_args.cache_dir , ) lowercase_ : Union[str, Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}''' , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported lowercase_ : str = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=__snake_case ) def prepare_dataset(__snake_case : int ): # check that all files have the correct sampling rate lowercase_ , lowercase_ : List[str] = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays lowercase_ : Dict = datasets.map( __snake_case , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets['''train'''].column_names ) # filter audio files that are too long lowercase_ : Union[str, Any] = vectorized_datasets.filter( lambda __snake_case : len(data['''speech'''] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(__snake_case : Tuple ): return feature_extractor(batch['''speech'''] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` lowercase_ : Union[str, Any] = vectorized_datasets.map( __snake_case , batched=__snake_case , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets['''train'''].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 lowercase_ : str = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( '''PreTraining is only supported for ``config.do_stable_layer_norm=True`` and''' ''' ``config.feat_extract_norm=\'layer\'''' ) lowercase_ : Optional[int] = WavaVecaForPreTraining(__snake_case ) lowercase_ : Union[str, Any] = DataCollatorForWavaVecaPretraining(model=__snake_case , feature_extractor=__snake_case ) lowercase_ : Dict = WavaVecaPreTrainer( model=__snake_case , data_collator=__snake_case , args=__snake_case , train_dataset=vectorized_datasets['''train'''] , eval_dataset=vectorized_datasets['''validation'''] , tokenizer=__snake_case , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
33
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : list[int] ) -> None: A = len(A_ ) A = [0] * len_array if len_array > 0: A = array[0] for i in range(1 ,A_ ): A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ) -> bool: A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(A_ ) return False if __name__ == "__main__": import doctest doctest.testmod()
74
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, ) A ={ 'configuration_xlm_roberta': [ 'XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaConfig', 'XLMRobertaOnnxConfig', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =['XLMRobertaTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =['XLMRobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =[ 'XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMRobertaForCausalLM', 'XLMRobertaForMaskedLM', 'XLMRobertaForMultipleChoice', 'XLMRobertaForQuestionAnswering', 'XLMRobertaForSequenceClassification', 'XLMRobertaForTokenClassification', 'XLMRobertaModel', 'XLMRobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =[ 'TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLMRobertaForCausalLM', 'TFXLMRobertaForMaskedLM', 'TFXLMRobertaForMultipleChoice', 'TFXLMRobertaForQuestionAnswering', 'TFXLMRobertaForSequenceClassification', 'TFXLMRobertaForTokenClassification', 'TFXLMRobertaModel', 'TFXLMRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =[ 'FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxXLMRobertaForMaskedLM', 'FlaxXLMRobertaForCausalLM', 'FlaxXLMRobertaForMultipleChoice', 'FlaxXLMRobertaForQuestionAnswering', 'FlaxXLMRobertaForSequenceClassification', 'FlaxXLMRobertaForTokenClassification', 'FlaxXLMRobertaModel', 'FlaxXLMRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = RobertaPreLayerNormConfig.from_pretrained( snake_case__ , architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict A = torch.load(hf_hub_download(repo_id=snake_case__ , filename='pytorch_model.bin' ) ) A = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): A = 'roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue A = tensor_value A = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=snake_case__ , config=snake_case__ , state_dict=snake_case__ ) model.save_pretrained(snake_case__ ) # convert tokenizer A = AutoTokenizer.from_pretrained(snake_case__ ) tokenizer.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
74
0
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets __a = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" __a = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" __a = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: return float((preds == labels).mean() ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> Any: snake_case__ : Any = simple_accuracy(_lowerCAmelCase , _lowerCAmelCase ) snake_case__ : int = float(fa_score(y_true=_lowerCAmelCase , y_pred=_lowerCAmelCase ) ) return { "accuracy": acc, "f1": fa, } def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> str: snake_case__ : Dict = np.array(_lowerCAmelCase ) snake_case__ : Any = np.array(_lowerCAmelCase ) snake_case__ : Any = en_sentvecs.shape[0] # mean centering snake_case__ : Tuple = en_sentvecs - np.mean(_lowerCAmelCase , axis=0 ) snake_case__ : Dict = in_sentvecs - np.mean(_lowerCAmelCase , axis=0 ) snake_case__ : List[str] = cdist(_lowerCAmelCase , _lowerCAmelCase , """cosine""" ) snake_case__ : List[Any] = np.array(range(_lowerCAmelCase ) ) snake_case__ : Tuple = sim.argsort(axis=1 )[:, :10] snake_case__ : List[str] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def lowerCamelCase ( self : str ): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", """ """\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", """ """\"wiki-ner\"]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" ) if self.config_name != """cvit-mkb-clsr""" else datasets.Sequence(datasets.Value("""float32""" ) ), """references""": datasets.Value("""int64""" ) if self.config_name != """cvit-mkb-clsr""" else datasets.Sequence(datasets.Value("""float32""" ) ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if self.config_name != """cvit-mkb-clsr""" else None , ) def lowerCamelCase ( self : str , snake_case_ : Dict , snake_case_ : Optional[int] ): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(snake_case_ , snake_case_ )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(snake_case_ , snake_case_ ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(snake_case_ , snake_case_ )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", """ """\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", """ """\"wiki-ner\"]""" )
35
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''roformer''' def __init__( self : Tuple ,A_ : Optional[int]=5_0000 ,A_ : Tuple=None ,A_ : Optional[Any]=768 ,A_ : Dict=12 ,A_ : Optional[int]=12 ,A_ : Union[str, Any]=3072 ,A_ : Dict="gelu" ,A_ : Dict=0.1 ,A_ : List[Any]=0.1 ,A_ : List[Any]=1536 ,A_ : List[str]=2 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : Optional[int]=0 ,A_ : List[str]=False ,A_ : Tuple=True ,**A_ : List[str] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size if embedding_size is None else embedding_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = rotary_value A = use_cache class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
74
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCAmelCase_ ( a , a , a , unittest.TestCase): lowerCamelCase__ = StableDiffusionInpaintPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCamelCase__ = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCamelCase__ = frozenset([]) def snake_case__ ( self): '''simple docstring''' torch.manual_seed(0) _lowerCAmelCase : str = UNetaDConditionModel( block_out_channels=(32, 64), layers_per_block=2, sample_size=32, in_channels=9, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=32, attention_head_dim=(2, 4), use_linear_projection=__a, ) _lowerCAmelCase : Optional[int] = PNDMScheduler(skip_prk_steps=__a) torch.manual_seed(0) _lowerCAmelCase : List[Any] = AutoencoderKL( block_out_channels=[32, 64], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, sample_size=128, ) torch.manual_seed(0) _lowerCAmelCase : Union[str, Any] = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=32, intermediate_size=37, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1000, hidden_act="gelu", projection_dim=512, ) _lowerCAmelCase : List[Any] = CLIPTextModel(__a) _lowerCAmelCase : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") _lowerCAmelCase : str = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def snake_case__ ( self, __a, __a=0): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = floats_tensor((1, 3, 32, 32), rng=random.Random(__a)).to(__a) _lowerCAmelCase : Optional[int] = image.cpu().permute(0, 2, 3, 1)[0] _lowerCAmelCase : Dict = Image.fromarray(np.uinta(__a)).convert("RGB").resize((64, 64)) _lowerCAmelCase : List[str] = Image.fromarray(np.uinta(image + 4)).convert("RGB").resize((64, 64)) if str(__a).startswith("mps"): _lowerCAmelCase : Any = torch.manual_seed(__a) else: _lowerCAmelCase : int = torch.Generator(device=__a).manual_seed(__a) _lowerCAmelCase : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "image": init_image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator _lowerCAmelCase : Union[str, Any] = self.get_dummy_components() _lowerCAmelCase : List[str] = StableDiffusionInpaintPipeline(**__a) _lowerCAmelCase : Tuple = sd_pipe.to(__a) sd_pipe.set_progress_bar_config(disable=__a) _lowerCAmelCase : List[Any] = self.get_dummy_inputs(__a) _lowerCAmelCase : Dict = sd_pipe(**__a).images _lowerCAmelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase : Tuple = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def snake_case__ ( self): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3) @slow @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase): def snake_case__ ( self): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png") _lowerCAmelCase : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png") _lowerCAmelCase : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint" "/yellow_cat_sitting_on_a_park_bench.npy") _lowerCAmelCase : List[Any] = "stabilityai/stable-diffusion-2-inpainting" _lowerCAmelCase : int = StableDiffusionInpaintPipeline.from_pretrained(__a, safety_checker=__a) pipe.to(__a) pipe.set_progress_bar_config(disable=__a) pipe.enable_attention_slicing() _lowerCAmelCase : Tuple = "Face of a yellow cat, high resolution, sitting on a park bench" _lowerCAmelCase : List[str] = torch.manual_seed(0) _lowerCAmelCase : Optional[Any] = pipe( prompt=__a, image=__a, mask_image=__a, generator=__a, output_type="np", ) _lowerCAmelCase : Any = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image).max() < 9E-3 def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : str = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png") _lowerCAmelCase : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png") _lowerCAmelCase : str = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint" "/yellow_cat_sitting_on_a_park_bench_fp16.npy") _lowerCAmelCase : Optional[Any] = "stabilityai/stable-diffusion-2-inpainting" _lowerCAmelCase : Any = StableDiffusionInpaintPipeline.from_pretrained( __a, torch_dtype=torch.floataa, safety_checker=__a, ) pipe.to(__a) pipe.set_progress_bar_config(disable=__a) pipe.enable_attention_slicing() _lowerCAmelCase : Optional[Any] = "Face of a yellow cat, high resolution, sitting on a park bench" _lowerCAmelCase : Optional[Any] = torch.manual_seed(0) _lowerCAmelCase : Tuple = pipe( prompt=__a, image=__a, mask_image=__a, generator=__a, output_type="np", ) _lowerCAmelCase : List[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image).max() < 5E-1 def snake_case__ ( self): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowerCAmelCase : int = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png") _lowerCAmelCase : Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png") _lowerCAmelCase : Optional[Any] = "stabilityai/stable-diffusion-2-inpainting" _lowerCAmelCase : Tuple = PNDMScheduler.from_pretrained(__a, subfolder="scheduler") _lowerCAmelCase : int = StableDiffusionInpaintPipeline.from_pretrained( __a, safety_checker=__a, scheduler=__a, torch_dtype=torch.floataa, ) pipe.to(__a) pipe.set_progress_bar_config(disable=__a) pipe.enable_attention_slicing(1) pipe.enable_sequential_cpu_offload() _lowerCAmelCase : Tuple = "Face of a yellow cat, high resolution, sitting on a park bench" _lowerCAmelCase : int = torch.manual_seed(0) _lowerCAmelCase : Union[str, Any] = pipe( prompt=__a, image=__a, mask_image=__a, generator=__a, num_inference_steps=2, output_type="np", ) _lowerCAmelCase : str = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
36
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : Dict ): A = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : int ): A , A = emb.weight.shape A = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A = emb.weight.data return lin_layer def _snake_case ( snake_case__ : List[str] , snake_case__ : Any="facebook/mbart-large-en-ro" , snake_case__ : Optional[int]=False , snake_case__ : List[str]=False ): A = torch.load(snake_case__ , map_location='cpu' )['model'] remove_ignore_keys_(snake_case__ ) A = state_dict['encoder.embed_tokens.weight'].shape[0] A = MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: A = 'relu' A = state_dict['decoder.embed_tokens.weight'] A = MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: A = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowercase = 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''') _lowercase = parser.parse_args() _lowercase = 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)
74
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : str = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: lowerCAmelCase__ : Union[str, Any] = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: lowerCAmelCase__ : int = 4 lowerCAmelCase__ : List[str] = 48 lowerCAmelCase__ : List[Any] = """pixelshuffle_aux""" elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: lowerCAmelCase__ : List[Any] = [6, 6, 6, 6] lowerCAmelCase__ : List[str] = 60 lowerCAmelCase__ : Tuple = [6, 6, 6, 6] lowerCAmelCase__ : Optional[Any] = """pixelshuffledirect""" elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: lowerCAmelCase__ : List[Any] = 4 lowerCAmelCase__ : int = """nearest+conv""" elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: lowerCAmelCase__ : List[Any] = 1 lowerCAmelCase__ : int = 1 lowerCAmelCase__ : Optional[Any] = 126 lowerCAmelCase__ : str = 7 lowerCAmelCase__ : Union[str, Any] = 255.0 lowerCAmelCase__ : Optional[int] = """""" return config def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" if "patch_embed.proj" in name and "layers" not in name: lowerCAmelCase__ : Dict = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: lowerCAmelCase__ : List[Any] = name.replace("""patch_embed.norm""" , """embeddings.patch_embeddings.layernorm""" ) if "layers" in name: lowerCAmelCase__ : Dict = name.replace("""layers""" , """encoder.stages""" ) if "residual_group.blocks" in name: lowerCAmelCase__ : List[Any] = name.replace("""residual_group.blocks""" , """layers""" ) if "attn.proj" in name: lowerCAmelCase__ : Any = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: lowerCAmelCase__ : Union[str, Any] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: lowerCAmelCase__ : Any = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: lowerCAmelCase__ : List[str] = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: lowerCAmelCase__ : str = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: lowerCAmelCase__ : Any = name.replace("""mlp.fc2""" , """output.dense""" ) if "q_bias" in name: lowerCAmelCase__ : int = name.replace("""q_bias""" , """query.bias""" ) if "k_bias" in name: lowerCAmelCase__ : Any = name.replace("""k_bias""" , """key.bias""" ) if "v_bias" in name: lowerCAmelCase__ : List[str] = name.replace("""v_bias""" , """value.bias""" ) if "cpb_mlp" in name: lowerCAmelCase__ : Optional[Any] = name.replace("""cpb_mlp""" , """continuous_position_bias_mlp""" ) if "patch_embed.proj" in name: lowerCAmelCase__ : Optional[Any] = name.replace("""patch_embed.proj""" , """patch_embed.projection""" ) if name == "norm.weight": lowerCAmelCase__ : Any = """layernorm.weight""" if name == "norm.bias": lowerCAmelCase__ : Optional[Any] = """layernorm.bias""" if "conv_first" in name: lowerCAmelCase__ : Tuple = name.replace("""conv_first""" , """first_convolution""" ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: lowerCAmelCase__ : Any = name.replace("""conv_last""" , """final_convolution""" ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: lowerCAmelCase__ : Union[str, Any] = name.replace("""conv_before_upsample.0""" , """conv_before_upsample""" ) if "upsample.0" in name: lowerCAmelCase__ : Optional[int] = name.replace("""upsample.0""" , """upsample.convolution_0""" ) if "upsample.2" in name: lowerCAmelCase__ : Optional[int] = name.replace("""upsample.2""" , """upsample.convolution_1""" ) lowerCAmelCase__ : int = """upsample.""" + name elif config.upsampler == "pixelshuffledirect": lowerCAmelCase__ : str = name.replace("""upsample.0.weight""" , """upsample.conv.weight""" ) lowerCAmelCase__ : List[str] = name.replace("""upsample.0.bias""" , """upsample.conv.bias""" ) else: pass else: lowerCAmelCase__ : Any = """swin2sr.""" + name return name def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" for key in orig_state_dict.copy().keys(): lowerCAmelCase__ : Optional[Any] = orig_state_dict.pop(UpperCamelCase ) if "qkv" in key: lowerCAmelCase__ : Dict = key.split(""".""" ) lowerCAmelCase__ : Any = int(key_split[1] ) lowerCAmelCase__ : Dict = int(key_split[4] ) lowerCAmelCase__ : List[str] = config.embed_dim if "weight" in key: lowerCAmelCase__ : List[str] = val[:dim, :] lowerCAmelCase__ : int = val[dim : dim * 2, :] lowerCAmelCase__ : Dict = val[-dim:, :] else: lowerCAmelCase__ : Union[str, Any] = val[:dim] lowerCAmelCase__ : Optional[Any] = val[dim : dim * 2] lowerCAmelCase__ : List[Any] = val[-dim:] pass else: lowerCAmelCase__ : Optional[int] = val return orig_state_dict def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[Any] = get_config(UpperCamelCase ) lowerCAmelCase__ : Any = SwinaSRForImageSuperResolution(UpperCamelCase ) model.eval() lowerCAmelCase__ : Tuple = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location="""cpu""" ) lowerCAmelCase__ : Optional[Any] = convert_state_dict(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ , lowerCAmelCase__ : Dict = model.load_state_dict(UpperCamelCase , strict=UpperCamelCase ) if len(UpperCamelCase ) > 0: raise ValueError("""Missing keys when converting: {}""".format(UpperCamelCase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(f"""Unexpected key {key} in state_dict""" ) # verify values lowerCAmelCase__ : Union[str, Any] = """https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true""" lowerCAmelCase__ : Dict = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ).convert("""RGB""" ) lowerCAmelCase__ : int = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values lowerCAmelCase__ : str = 126 if """Jpeg""" in checkpoint_url else 256 lowerCAmelCase__ : List[Any] = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) lowerCAmelCase__ : Optional[int] = transforms(UpperCamelCase ).unsqueeze(0 ) if config.num_channels == 1: lowerCAmelCase__ : int = pixel_values[:, 0, :, :].unsqueeze(1 ) lowerCAmelCase__ : Optional[Any] = model(UpperCamelCase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: lowerCAmelCase__ : Tuple = torch.Size([1, 3, 512, 512] ) lowerCAmelCase__ : Optional[Any] = torch.tensor( [[-0.7087, -0.7138, -0.6721], [-0.8340, -0.8095, -0.7298], [-0.9149, -0.8414, -0.7940]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: lowerCAmelCase__ : Union[str, Any] = torch.Size([1, 3, 1024, 1024] ) lowerCAmelCase__ : str = torch.tensor( [[-0.7775, -0.8105, -0.8933], [-0.7764, -0.8356, -0.9225], [-0.7976, -0.8686, -0.9579]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here lowerCAmelCase__ : str = torch.Size([1, 3, 1024, 1024] ) lowerCAmelCase__ : Dict = torch.tensor( [[-0.8035, -0.7504, -0.7491], [-0.8538, -0.8124, -0.7782], [-0.8804, -0.8651, -0.8493]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: lowerCAmelCase__ : Tuple = torch.Size([1, 3, 512, 512] ) lowerCAmelCase__ : Dict = torch.tensor( [[-0.7669, -0.8662, -0.8767], [-0.8810, -0.9962, -0.9820], [-0.9340, -1.0322, -1.1149]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: lowerCAmelCase__ : Tuple = torch.Size([1, 3, 1024, 1024] ) lowerCAmelCase__ : int = torch.tensor( [[-0.5238, -0.5557, -0.6321], [-0.6016, -0.5903, -0.6391], [-0.6244, -0.6334, -0.6889]] ) assert ( outputs.reconstruction.shape == expected_shape ), f"""Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}""" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , UpperCamelCase , atol=1e-3 ) print("""Looks ok!""" ) lowerCAmelCase__ : Optional[Any] = { """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth""": ( """swin2SR-classical-sr-x2-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth""": ( """swin2SR-classical-sr-x4-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth""": ( """swin2SR-compressed-sr-x4-48""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth""": ( """swin2SR-lightweight-x2-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth""": ( """swin2SR-realworld-sr-x4-64-bsrgan-psnr""" ), } lowerCAmelCase__ : Optional[int] = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(UpperCamelCase ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(UpperCamelCase ) if push_to_hub: model.push_to_hub(f"""caidas/{model_name}""" ) processor.push_to_hub(f"""caidas/{model_name}""" ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''', type=str, help='''URL of the original Swin2SR checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the converted model to the hub.''') _lowerCAmelCase = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
37
"""simple docstring""" import argparse import struct import unittest class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : bytes ) -> None: A = data # Initialize hash values A = [ 0X6_A_0_9_E_6_6_7, 0XB_B_6_7_A_E_8_5, 0X3_C_6_E_F_3_7_2, 0XA_5_4_F_F_5_3_A, 0X5_1_0_E_5_2_7_F, 0X9_B_0_5_6_8_8_C, 0X1_F_8_3_D_9_A_B, 0X5_B_E_0_C_D_1_9, ] # Initialize round constants A = [ 0X4_2_8_A_2_F_9_8, 0X7_1_3_7_4_4_9_1, 0XB_5_C_0_F_B_C_F, 0XE_9_B_5_D_B_A_5, 0X3_9_5_6_C_2_5_B, 0X5_9_F_1_1_1_F_1, 0X9_2_3_F_8_2_A_4, 0XA_B_1_C_5_E_D_5, 0XD_8_0_7_A_A_9_8, 0X1_2_8_3_5_B_0_1, 0X2_4_3_1_8_5_B_E, 0X5_5_0_C_7_D_C_3, 0X7_2_B_E_5_D_7_4, 0X8_0_D_E_B_1_F_E, 0X9_B_D_C_0_6_A_7, 0XC_1_9_B_F_1_7_4, 0XE_4_9_B_6_9_C_1, 0XE_F_B_E_4_7_8_6, 0X0_F_C_1_9_D_C_6, 0X2_4_0_C_A_1_C_C, 0X2_D_E_9_2_C_6_F, 0X4_A_7_4_8_4_A_A, 0X5_C_B_0_A_9_D_C, 0X7_6_F_9_8_8_D_A, 0X9_8_3_E_5_1_5_2, 0XA_8_3_1_C_6_6_D, 0XB_0_0_3_2_7_C_8, 0XB_F_5_9_7_F_C_7, 0XC_6_E_0_0_B_F_3, 0XD_5_A_7_9_1_4_7, 0X0_6_C_A_6_3_5_1, 0X1_4_2_9_2_9_6_7, 0X2_7_B_7_0_A_8_5, 0X2_E_1_B_2_1_3_8, 0X4_D_2_C_6_D_F_C, 0X5_3_3_8_0_D_1_3, 0X6_5_0_A_7_3_5_4, 0X7_6_6_A_0_A_B_B, 0X8_1_C_2_C_9_2_E, 0X9_2_7_2_2_C_8_5, 0XA_2_B_F_E_8_A_1, 0XA_8_1_A_6_6_4_B, 0XC_2_4_B_8_B_7_0, 0XC_7_6_C_5_1_A_3, 0XD_1_9_2_E_8_1_9, 0XD_6_9_9_0_6_2_4, 0XF_4_0_E_3_5_8_5, 0X1_0_6_A_A_0_7_0, 0X1_9_A_4_C_1_1_6, 0X1_E_3_7_6_C_0_8, 0X2_7_4_8_7_7_4_C, 0X3_4_B_0_B_C_B_5, 0X3_9_1_C_0_C_B_3, 0X4_E_D_8_A_A_4_A, 0X5_B_9_C_C_A_4_F, 0X6_8_2_E_6_F_F_3, 0X7_4_8_F_8_2_E_E, 0X7_8_A_5_6_3_6_F, 0X8_4_C_8_7_8_1_4, 0X8_C_C_7_0_2_0_8, 0X9_0_B_E_F_F_F_A, 0XA_4_5_0_6_C_E_B, 0XB_E_F_9_A_3_F_7, 0XC_6_7_1_7_8_F_2, ] A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : bytes ) -> bytes: A = B'\x80' + (B'\x00' * (63 - (len(A_ ) + 8) % 64)) A = struct.pack('>Q' ,(len(A_ ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: # Convert into blocks of 64 bytes A = [ self.preprocessed_data[x : x + 64] for x in range(0 ,len(self.preprocessed_data ) ,64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers A = list(struct.unpack('>16L' ,A_ ) ) # add 48 0-ed integers words += [0] * 48 A , A , A , A , A , A , A , A = self.hashes for index in range(0 ,64 ): if index > 15: # modify the zero-ed indexes at the end of the array A = ( self.ror(words[index - 15] ,7 ) ^ self.ror(words[index - 15] ,18 ) ^ (words[index - 15] >> 3) ) A = ( self.ror(words[index - 2] ,17 ) ^ self.ror(words[index - 2] ,19 ) ^ (words[index - 2] >> 10) ) A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0_0_0_0_0_0_0_0 # Compression A = self.ror(A_ ,6 ) ^ self.ror(A_ ,11 ) ^ self.ror(A_ ,25 ) A = (e & f) ^ ((~e & 0XF_F_F_F_F_F_F_F) & g) A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0_0_0_0_0_0_0_0 A = self.ror(A_ ,2 ) ^ self.ror(A_ ,13 ) ^ self.ror(A_ ,22 ) A = (a & b) ^ (a & c) ^ (b & c) A = (sa + maj) % 0X1_0_0_0_0_0_0_0_0 A , A , A , A , A , A , A , A = ( g, f, e, ((d + tempa) % 0X1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0X1_0_0_0_0_0_0_0_0), ) A = [a, b, c, d, e, f, g, h] # Modify final values A = [ ((element + mutated_hash_values[index]) % 0X1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] A = ''.join([hex(A_ )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : int ) -> int: return 0XF_F_F_F_F_F_F_F & (value << (32 - rotations)) | (value >> rotations) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> None: import hashlib A = bytes('Test String' ,'utf-8' ) self.assertEqual(SHAaaa(A_ ).hash ,hashlib.shaaaa(A_ ).hexdigest() ) def _snake_case ( ): import doctest doctest.testmod() A = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) A = parser.parse_args() A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: A = f.read() else: A = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
74
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : List[str] ): UpperCamelCase :int = tempfile.mkdtemp() # fmt: off UpperCamelCase :str = ["""""", """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on UpperCamelCase :Optional[int] = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) UpperCamelCase :List[str] = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] UpperCamelCase :List[str] = {"""unk_token""": """<unk>"""} UpperCamelCase :List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase :Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__lowerCamelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__lowerCamelCase ) ) UpperCamelCase :List[Any] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } UpperCamelCase :Optional[Any] = os.path.join(self.tmpdirname , __lowerCamelCase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__lowerCamelCase , __lowerCamelCase ) def _A ( self : Dict , **__lowerCamelCase : Dict ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token="""!""" , **__lowerCamelCase ) def _A ( self : str , **__lowerCamelCase : Any ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token="""!""" , **__lowerCamelCase ) def _A ( self : Tuple , **__lowerCamelCase : List[Any] ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def _A ( self : str ): shutil.rmtree(self.tmpdirname ) def _A ( self : str ): UpperCamelCase :Any = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] UpperCamelCase :Any = [Image.fromarray(np.moveaxis(__lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self : str ): UpperCamelCase :List[Any] = self.get_tokenizer() UpperCamelCase :List[Any] = self.get_rust_tokenizer() UpperCamelCase :Tuple = self.get_image_processor() UpperCamelCase :Any = OwlViTProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) processor_slow.save_pretrained(self.tmpdirname ) UpperCamelCase :int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = OwlViTProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) processor_fast.save_pretrained(self.tmpdirname ) UpperCamelCase :str = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __lowerCamelCase ) self.assertIsInstance(processor_fast.tokenizer , __lowerCamelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __lowerCamelCase ) self.assertIsInstance(processor_fast.image_processor , __lowerCamelCase ) def _A ( self : List[str] ): UpperCamelCase :Optional[int] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase :Any = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCamelCase :str = self.get_image_processor(do_normalize=__lowerCamelCase ) UpperCamelCase :str = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__lowerCamelCase ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCamelCase ) def _A ( self : Union[str, Any] ): UpperCamelCase :Union[str, Any] = self.get_image_processor() UpperCamelCase :Dict = self.get_tokenizer() UpperCamelCase :Optional[int] = OwlViTProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) UpperCamelCase :Dict = self.prepare_image_inputs() UpperCamelCase :List[Any] = image_processor(__lowerCamelCase , return_tensors="""np""" ) UpperCamelCase :Dict = processor(images=__lowerCamelCase , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _A ( self : Dict ): UpperCamelCase :List[Any] = self.get_image_processor() UpperCamelCase :str = self.get_tokenizer() UpperCamelCase :List[Any] = OwlViTProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) UpperCamelCase :Optional[Any] = """lower newer""" UpperCamelCase :List[str] = processor(text=__lowerCamelCase , return_tensors="""np""" ) UpperCamelCase :List[str] = tokenizer(__lowerCamelCase , return_tensors="""np""" ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def _A ( self : Optional[int] ): UpperCamelCase :List[str] = self.get_image_processor() UpperCamelCase :Union[str, Any] = self.get_tokenizer() UpperCamelCase :Any = OwlViTProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) UpperCamelCase :Optional[int] = """lower newer""" UpperCamelCase :Tuple = self.prepare_image_inputs() UpperCamelCase :int = processor(text=__lowerCamelCase , images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _A ( self : Any ): UpperCamelCase :Optional[Any] = """google/owlvit-base-patch32""" UpperCamelCase :List[Any] = OwlViTProcessor.from_pretrained(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = ["""cat""", """nasa badge"""] UpperCamelCase :str = processor(text=__lowerCamelCase ) UpperCamelCase :Optional[Any] = 16 self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _A ( self : List[str] ): UpperCamelCase :Dict = """google/owlvit-base-patch32""" UpperCamelCase :Dict = OwlViTProcessor.from_pretrained(__lowerCamelCase ) UpperCamelCase :Tuple = [["""cat""", """nasa badge"""], ["""person"""]] UpperCamelCase :Union[str, Any] = processor(text=__lowerCamelCase ) UpperCamelCase :int = 16 UpperCamelCase :int = len(__lowerCamelCase ) UpperCamelCase :Dict = max([len(__lowerCamelCase ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _A ( self : Any ): UpperCamelCase :Optional[Any] = """google/owlvit-base-patch32""" UpperCamelCase :List[Any] = OwlViTProcessor.from_pretrained(__lowerCamelCase ) UpperCamelCase :Optional[int] = ["""cat""", """nasa badge"""] UpperCamelCase :Union[str, Any] = processor(text=__lowerCamelCase ) UpperCamelCase :str = 16 UpperCamelCase :Optional[int] = inputs["""input_ids"""] UpperCamelCase :str = [ [49_406, 2_368, 49_407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49_406, 6_841, 11_301, 49_407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def _A ( self : str ): UpperCamelCase :Union[str, Any] = self.get_image_processor() UpperCamelCase :str = self.get_tokenizer() UpperCamelCase :Optional[int] = OwlViTProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) UpperCamelCase :List[Any] = self.prepare_image_inputs() UpperCamelCase :List[str] = self.prepare_image_inputs() UpperCamelCase :Union[str, Any] = processor(images=__lowerCamelCase , query_images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ["""query_pixel_values""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def _A ( self : Dict ): UpperCamelCase :Dict = self.get_image_processor() UpperCamelCase :str = self.get_tokenizer() UpperCamelCase :str = OwlViTProcessor(tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase ) UpperCamelCase :str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase :Any = processor.batch_decode(__lowerCamelCase ) UpperCamelCase :Optional[Any] = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase )
38
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''DeiTFeatureExtractor'''] _lowercase = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDeiTForImageClassification''', '''TFDeiTForImageClassificationWithTeacher''', '''TFDeiTForMaskedImageModeling''', '''TFDeiTModel''', '''TFDeiTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
0
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib _a = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } _a = logging.WARNING def __A ( )-> Tuple: """simple docstring""" _UpperCAmelCase = os.getenv('DATASETS_VERBOSITY' , __lowerCAmelCase ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F"""Unknown option DATASETS_VERBOSITY={env_level_str}, """ F"""has to be one of: { ", ".join(log_levels.keys() ) }""" ) return _default_log_level def __A ( )-> str: """simple docstring""" return __name__.split('.' )[0] def __A ( )-> logging.Logger: """simple docstring""" return logging.getLogger(_get_library_name() ) def __A ( )-> None: """simple docstring""" _UpperCAmelCase = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def __A ( )-> None: """simple docstring""" _UpperCAmelCase = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def __A ( __lowerCAmelCase = None )-> logging.Logger: """simple docstring""" if name is None: _UpperCAmelCase = _get_library_name() return logging.getLogger(__lowerCAmelCase ) def __A ( )-> int: """simple docstring""" return _get_library_root_logger().getEffectiveLevel() def __A ( __lowerCAmelCase )-> None: """simple docstring""" _get_library_root_logger().setLevel(__lowerCAmelCase ) def __A ( )-> Dict: """simple docstring""" return set_verbosity(__lowerCAmelCase ) def __A ( )-> Optional[int]: """simple docstring""" return set_verbosity(__lowerCAmelCase ) def __A ( )-> Tuple: """simple docstring""" return set_verbosity(__lowerCAmelCase ) def __A ( )-> Optional[int]: """simple docstring""" return set_verbosity(__lowerCAmelCase ) def __A ( )-> None: """simple docstring""" _UpperCAmelCase = False def __A ( )-> None: """simple docstring""" _UpperCAmelCase = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class __lowerCamelCase : """simple docstring""" def __init__( self , *UpperCAmelCase , **UpperCAmelCase ): # pylint: disable=unused-argument """simple docstring""" _UpperCAmelCase = args[0] if args else None def __iter__( self ): """simple docstring""" return iter(self._iterator ) def __getattr__( self , UpperCAmelCase ): """simple docstring""" def empty_fn(*UpperCAmelCase , **UpperCAmelCase ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ): """simple docstring""" return self def __exit__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): """simple docstring""" return _a = True class __lowerCamelCase : """simple docstring""" def __call__( self , *UpperCAmelCase , UpperCAmelCase=False , **UpperCAmelCase ): """simple docstring""" if _tqdm_active and not disable: return tqdm_lib.tqdm(*UpperCAmelCase , **UpperCAmelCase ) else: return EmptyTqdm(*UpperCAmelCase , **UpperCAmelCase ) def UpperCamelCase ( self , *UpperCAmelCase , **UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*UpperCAmelCase , **UpperCAmelCase ) def UpperCamelCase ( self ): """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() _a = _tqdm_cls() def __A ( )-> bool: """simple docstring""" global _tqdm_active return bool(_tqdm_active ) def __A ( )-> Dict: """simple docstring""" global _tqdm_active _UpperCAmelCase = True def __A ( )-> str: """simple docstring""" global _tqdm_active _UpperCAmelCase = False
39
"""simple docstring""" from __future__ import annotations import requests def _snake_case ( snake_case__ : str ): A = F'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case__ ).json() def _snake_case ( snake_case__ : int = 10 ): A = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' A = requests.get(snake_case__ ).json()[:max_stories] return [get_hackernews_story(snake_case__ ) for story_id in story_ids] def _snake_case ( snake_case__ : int = 10 ): A = hackernews_top_stories(snake_case__ ) return "\n".join('* [{title}]({url})'.format(**snake_case__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
74
0
"""simple docstring""" __lowercase = { "joule": 1.0, "kilojoule": 1000, "megajoule": 1000000, "gigajoule": 1000000000, "wattsecond": 1.0, "watthour": 3600, "kilowatthour": 3600000, "newtonmeter": 1.0, "calorie_nutr": 4186.8, "kilocalorie_nutr": 4186800.00, "electronvolt": 1.602176634e-19, "britishthermalunit_it": 1055.05585, "footpound": 1.35_58_18, } def lowercase ( A_ , A_ , A_ )-> float: '''simple docstring''' if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: a : Optional[int] = ( F'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' F'''Valid values are: {", ".join(A_ )}''' ) raise ValueError(A_ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
40
"""simple docstring""" from string import ascii_uppercase _lowercase = {char: i for i, char in enumerate(ascii_uppercase)} _lowercase = dict(enumerate(ascii_uppercase)) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = len(snake_case__ ) A = 0 while True: if x == i: A = 0 if len(snake_case__ ) == len(snake_case__ ): break key += key[i] i += 1 return key def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in message: if letter == " ": cipher_text += " " else: A = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: A = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _snake_case ( ): A = 'THE GERMAN ATTACK' A = 'SECRET' A = generate_key(snake_case__ , snake_case__ ) A = cipher_text(snake_case__ , snake_case__ ) print(F'Encrypted Text = {s}' ) print(F'Original Text = {original_text(snake_case__ , snake_case__ )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
74
0
'''simple docstring''' import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class _lowercase : def __init__( self: List[str] , UpperCamelCase__: Dict , UpperCamelCase__: Dict=13 , UpperCamelCase__: int=30 , UpperCamelCase__: Tuple=2 , UpperCamelCase__: Any=3 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: Optional[int]=32 , UpperCamelCase__: Tuple=5 , UpperCamelCase__: Any=4 , UpperCamelCase__: str=37 , UpperCamelCase__: Union[str, Any]="gelu" , UpperCamelCase__: str=0.1 , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: Union[str, Any]=10 , UpperCamelCase__: Optional[Any]=0.02 , UpperCamelCase__: Optional[Any]=3 , UpperCamelCase__: Any=None , UpperCamelCase__: Any=2 , ): lowerCamelCase__ : str = parent lowerCamelCase__ : List[str] = batch_size lowerCamelCase__ : Tuple = image_size lowerCamelCase__ : Any = patch_size lowerCamelCase__ : Dict = num_channels lowerCamelCase__ : List[str] = is_training lowerCamelCase__ : Dict = use_labels lowerCamelCase__ : List[str] = hidden_size lowerCamelCase__ : str = num_hidden_layers lowerCamelCase__ : Any = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : int = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : int = type_sequence_label_size lowerCamelCase__ : Tuple = initializer_range lowerCamelCase__ : Optional[int] = scope lowerCamelCase__ : Tuple = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) lowerCamelCase__ : str = (image_size // patch_size) ** 2 lowerCamelCase__ : int = num_patches + 2 def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[int] = None if self.use_labels: lowerCamelCase__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Optional[int] = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self: Dict ): return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : Any = DeiTModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Dict , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : List[str] = DeiTForMaskedImageModeling(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Any = model(UpperCamelCase__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowerCamelCase__ : List[str] = 1 lowerCamelCase__ : Optional[int] = DeiTForMaskedImageModeling(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : int = model(UpperCamelCase__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: Tuple , UpperCamelCase__: List[str] ): lowerCamelCase__ : str = self.type_sequence_label_size lowerCamelCase__ : Union[str, Any] = DeiTForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCamelCase__ : List[Any] = 1 lowerCamelCase__ : List[Any] = DeiTForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : List[str] = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : Union[str, Any] = config_and_inputs lowerCamelCase__ : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) a = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) a = False a = False a = False def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : List[str] = DeiTModelTester(self ) lowerCamelCase__ : List[Any] = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: int ): self.config_tester.run_common_tests() @unittest.skip(reason="""DeiT does not use inputs_embeds""" ) def lowerCamelCase_ ( self: Optional[Any] ): pass def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ , lowerCamelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Optional[int] = model_class(UpperCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase__ : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase__ , nn.Linear ) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ , lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Optional[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Tuple = [*signature.parameters.keys()] lowerCamelCase__ : Dict = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__ ) def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Dict , UpperCamelCase__: List[str] , UpperCamelCase__: Dict=False ): lowerCamelCase__ : List[Any] = super()._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def lowerCamelCase_ ( self: Dict ): if not self.model_tester.is_training: return lowerCamelCase__ , lowerCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : List[str] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(UpperCamelCase__ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue lowerCamelCase__ : Optional[int] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.train() lowerCamelCase__ : Any = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) lowerCamelCase__ : str = model(**UpperCamelCase__ ).loss loss.backward() def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ , lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return lowerCamelCase__ : Tuple = False lowerCamelCase__ : Any = True for model_class in self.all_model_classes: if model_class in get_values(UpperCamelCase__ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue lowerCamelCase__ : Optional[int] = model_class(UpperCamelCase__ ) model.gradient_checkpointing_enable() model.to(UpperCamelCase__ ) model.train() lowerCamelCase__ : Optional[int] = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) lowerCamelCase__ : int = model(**UpperCamelCase__ ).loss loss.backward() def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ , lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : str = [ {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float}, {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long}, {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(UpperCamelCase__ ), *get_values(UpperCamelCase__ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): lowerCamelCase__ : int = problem_type["""title"""] lowerCamelCase__ : Any = problem_type["""num_labels"""] lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.train() lowerCamelCase__ : Dict = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) if problem_type["num_labels"] > 1: lowerCamelCase__ : List[Any] = inputs["""labels"""].unsqueeze(1 ).repeat(1 , problem_type["""num_labels"""] ) lowerCamelCase__ : List[Any] = inputs["""labels"""].to(problem_type["""dtype"""] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=UpperCamelCase__ ) as warning_list: lowerCamelCase__ : List[Any] = model(**UpperCamelCase__ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def lowerCamelCase_ ( self: Union[str, Any] ): for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Optional[Any] = DeiTModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> List[str]: lowerCamelCase__ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: List[Any] ): return ( DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Optional[int] = DeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ).to( UpperCamelCase__ ) lowerCamelCase__ : Dict = self.default_image_processor lowerCamelCase__ : Optional[int] = prepare_img() lowerCamelCase__ : str = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : List[str] = model(**UpperCamelCase__ ) # verify the logits lowerCamelCase__ : Union[str, Any] = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Any = torch.tensor([-1.0_266, 0.1_912, -1.2_861] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Optional[Any] = DeiTModel.from_pretrained( """facebook/deit-base-distilled-patch16-224""" , torch_dtype=torch.floataa , device_map="""auto""" ) lowerCamelCase__ : List[Any] = self.default_image_processor lowerCamelCase__ : List[str] = prepare_img() lowerCamelCase__ : Tuple = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ) lowerCamelCase__ : Optional[Any] = inputs.pixel_values.to(UpperCamelCase__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): lowerCamelCase__ : int = model(UpperCamelCase__ )
41
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ) -> Optional[Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] ,model_result['ss'] ): A = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = 'sgugger/tiny-distilbert-classification' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,only_pretrain_model=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,torchscript=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,fpaa=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) # set architectures equal to `None` A = None A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' ,'Can\'t do half precision' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,fpaa=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,save_to_csv=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,inference_time_csv_file=os.path.join(A_ ,'inf_time.csv' ) ,train_memory_csv_file=os.path.join(A_ ,'train_mem.csv' ) ,inference_memory_csv_file=os.path.join(A_ ,'inf_mem.csv' ) ,train_time_csv_file=os.path.join(A_ ,'train_time.csv' ) ,env_info_csv_file=os.path.join(A_ ,'env.csv' ) ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) benchmark.run() self.assertTrue(Path(os.path.join(A_ ,'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'env.csv' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(A_ : Optional[int] ): self.assertTrue(hasattr(A_ ,'sequential' ) ) self.assertTrue(hasattr(A_ ,'cumulative' ) ) self.assertTrue(hasattr(A_ ,'current' ) ) self.assertTrue(hasattr(A_ ,'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,log_filename=os.path.join(A_ ,'log.txt' ) ,log_print=A_ ,trace_memory_line_by_line=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A_ ,'log.txt' ) ).exists() )
74
0
'''simple docstring''' import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask lowercase : Tuple = logging.getLogger(__name__) class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = """token-classification""" def __init__( self , lowerCAmelCase_ ): """simple docstring""" if type(lowerCAmelCase_ ) == dict: _snake_case = Namespace(**lowerCAmelCase_ ) _snake_case = import_module('tasks' ) try: _snake_case = getattr(lowerCAmelCase_ , hparams.task_type ) _snake_case = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) _snake_case = self.token_classification_task.get_labels(hparams.labels ) _snake_case = CrossEntropyLoss().ignore_index super().__init__(lowerCAmelCase_ , len(self.labels ) , self.mode ) def lowerCamelCase ( self , **lowerCAmelCase_ ): """simple docstring""" return self.model(**lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type != "distilbert": _snake_case = ( batch[2] if self.config.model_type in ['bert', 'xlnet'] else None ) # XLM and RoBERTa don"t use token_type_ids _snake_case = self(**lowerCAmelCase_ ) _snake_case = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.hparams for mode in ["train", "dev", "test"]: _snake_case = self._feature_file(lowerCAmelCase_ ) if os.path.exists(lowerCAmelCase_ ) and not args.overwrite_cache: logger.info('Loading features from cached file %s' , lowerCAmelCase_ ) _snake_case = torch.load(lowerCAmelCase_ ) else: logger.info('Creating features from dataset file at %s' , args.data_dir ) _snake_case = self.token_classification_task.read_examples_from_file(args.data_dir , lowerCAmelCase_ ) _snake_case = self.token_classification_task.convert_examples_to_features( lowerCAmelCase_ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ['xlnet'] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ['xlnet'] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=lowerCAmelCase_ , pad_on_left=bool(self.config.model_type in ['xlnet'] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info('Saving features into cached file %s' , lowerCAmelCase_ ) torch.save(lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ): """simple docstring""" _snake_case = self._feature_file(lowerCAmelCase_ ) logger.info('Loading features from cached file %s' , lowerCAmelCase_ ) _snake_case = torch.load(lowerCAmelCase_ ) _snake_case = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) _snake_case = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: _snake_case = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: _snake_case = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) _snake_case = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) , batch_size=lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" """Compute validation""" "" _snake_case = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type != "distilbert": _snake_case = ( batch[2] if self.config.model_type in ['bert', 'xlnet'] else None ) # XLM and RoBERTa don"t use token_type_ids _snake_case = self(**lowerCAmelCase_ ) _snake_case , _snake_case = outputs[:2] _snake_case = logits.detach().cpu().numpy() _snake_case = inputs['labels'].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = torch.stack([x['val_loss'] for x in outputs] ).mean() _snake_case = np.concatenate([x['pred'] for x in outputs] , axis=0 ) _snake_case = np.argmax(lowerCAmelCase_ , axis=2 ) _snake_case = np.concatenate([x['target'] for x in outputs] , axis=0 ) _snake_case = dict(enumerate(self.labels ) ) _snake_case = [[] for _ in range(out_label_ids.shape[0] )] _snake_case = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) _snake_case = { 'val_loss': val_loss_mean, 'accuracy_score': accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), 'precision': precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), 'recall': recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), 'f1': fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } _snake_case = dict(results.items() ) _snake_case = results return ret, preds_list, out_label_list def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case , _snake_case = self._eval_end(lowerCAmelCase_ ) _snake_case = ret['log'] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case , _snake_case = self._eval_end(lowerCAmelCase_ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 _snake_case = ret['log'] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" BaseTransformer.add_model_specific_args(lowerCAmelCase_ , lowerCAmelCase_ ) parser.add_argument( '--task_type' , default='NER' , type=lowerCAmelCase_ , help='Task type to fine tune in training (e.g. NER, POS, etc)' ) parser.add_argument( '--max_seq_length' , default=1_28 , type=lowerCAmelCase_ , help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) , ) parser.add_argument( '--labels' , default='' , type=lowerCAmelCase_ , help='Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.' , ) parser.add_argument( '--gpus' , default=0 , type=lowerCAmelCase_ , help='The number of GPUs allocated for this, it is by default 0 meaning none' , ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) return parser if __name__ == "__main__": lowercase : List[Any] = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) lowercase : Union[str, Any] = NERTransformer.add_model_specific_args(parser, os.getcwd()) lowercase : Dict = parser.parse_args() lowercase : List[Any] = NERTransformer(args) lowercase : List[Any] = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 lowercase : int = sorted(glob.glob(os.path.join(args.output_dir, "checkpoint-epoch=*.ckpt"), recursive=True)) lowercase : Dict = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
42
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _lowercase = re.compile(r'''^(?P<major>\d+)''' r'''\.(?P<minor>\d+)''' r'''\.(?P<patch>\d+)$''') @total_ordering @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: A , A , A = _str_to_version_tuple(self.version_str ) def __repr__( self : Optional[int] ) -> Dict: return F'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return self.major, self.minor, self.patch def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Tuple ) -> Union[str, Any]: if isinstance(A_ ,A_ ): return Version(A_ ) elif isinstance(A_ ,A_ ): return other raise TypeError(F'{other} (type {type(A_ )}) cannot be compared to version.' ) def __eq__( self : List[Any] ,A_ : Dict ) -> Any: try: A = self._validate_operand(A_ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : List[Any] ,A_ : Optional[int] ) -> Tuple: A = self._validate_operand(A_ ) return self.tuple < other.tuple def __hash__( self : Union[str, Any] ) -> Union[str, Any]: return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[str] ) -> List[str]: A = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.version_str def _snake_case ( snake_case__ : List[str] ): A = _VERSION_REG.match(snake_case__ ) if not res: raise ValueError(F'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(snake_case__ ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def _snake_case ( snake_case__ : str ): return ".".join(str(snake_case__ ) for v in version_tuple )
74
0
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 lowerCamelCase_ : '''simple docstring''' def __init__( self , __lowercase , __lowercase=13 , __lowercase=30 , __lowercase=2 , __lowercase=3 , __lowercase=True , __lowercase=True , __lowercase=32 , __lowercase=2 , __lowercase=4 , __lowercase=37 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=10 , __lowercase=0.02 , __lowercase=3 , __lowercase=0.6 , __lowercase=None , ) -> Tuple: __UpperCamelCase :List[str] = parent __UpperCamelCase :List[Any] = batch_size __UpperCamelCase :str = image_size __UpperCamelCase :List[Any] = patch_size __UpperCamelCase :List[str] = num_channels __UpperCamelCase :Union[str, Any] = is_training __UpperCamelCase :List[str] = use_labels __UpperCamelCase :Tuple = hidden_size __UpperCamelCase :str = num_hidden_layers __UpperCamelCase :List[Any] = num_attention_heads __UpperCamelCase :Optional[Any] = intermediate_size __UpperCamelCase :List[str] = hidden_act __UpperCamelCase :str = hidden_dropout_prob __UpperCamelCase :List[str] = attention_probs_dropout_prob __UpperCamelCase :Union[str, Any] = type_sequence_label_size __UpperCamelCase :List[str] = initializer_range __UpperCamelCase :Optional[int] = mask_ratio __UpperCamelCase :Optional[int] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __UpperCamelCase :Optional[Any] = (image_size // patch_size) ** 2 __UpperCamelCase :Any = int(math.ceil((1 - mask_ratio) * (num_patches + 1))) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __UpperCamelCase :Tuple = None if self.use_labels: __UpperCamelCase :str = ids_tensor([self.batch_size] , self.type_sequence_label_size) __UpperCamelCase :List[Any] = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self) -> Tuple: 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=__lowercase , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> Any: __UpperCamelCase :Any = TFViTMAEModel(config=__lowercase) __UpperCamelCase :Union[str, Any] = model(__lowercase , training=__lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> List[str]: __UpperCamelCase :str = TFViTMAEForPreTraining(__lowercase) __UpperCamelCase :str = model(__lowercase , training=__lowercase) # expected sequence length = num_patches __UpperCamelCase :List[str] = (self.image_size // self.patch_size) ** 2 __UpperCamelCase :Union[str, Any] = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels)) # test greyscale images __UpperCamelCase :List[str] = 1 __UpperCamelCase :List[str] = TFViTMAEForPreTraining(__lowercase) __UpperCamelCase :int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __UpperCamelCase :Dict = model(__lowercase , training=__lowercase) __UpperCamelCase :List[str] = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels)) def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() ((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) :List[str] = config_and_inputs __UpperCamelCase :Dict = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : str = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () a__ : Dict = {"""feature-extraction""": TFViTMAEModel} if is_tf_available() else {} a__ : Tuple = False a__ : str = False a__ : Optional[Any] = False a__ : Union[str, Any] = False def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :List[str] = TFViTMAEModelTester(self) __UpperCamelCase :List[str] = ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37) def UpperCamelCase__ ( self) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMAE does not use inputs_embeds''') def UpperCamelCase__ ( self) -> str: pass def UpperCamelCase__ ( self) -> Any: __UpperCamelCase , __UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase :List[Any] = model_class(__lowercase) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer)) __UpperCamelCase :Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowercase , tf.keras.layers.Layer)) def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase , __UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase :Tuple = model_class(__lowercase) __UpperCamelCase :int = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase :Optional[int] = [*signature.parameters.keys()] __UpperCamelCase :Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase) def UpperCamelCase__ ( self) -> Any: __UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase) def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__lowercase) def UpperCamelCase__ ( self) -> Optional[Any]: # make the mask reproducible np.random.seed(2) __UpperCamelCase , __UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase :Tuple = int((config.image_size // config.patch_size) ** 2) __UpperCamelCase :Optional[int] = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) for model_class in self.all_model_classes: __UpperCamelCase :str = model_class(__lowercase) __UpperCamelCase :Optional[int] = self._prepare_for_class(__lowercase , __lowercase) __UpperCamelCase :Dict = model(__lowercase , noise=__lowercase) __UpperCamelCase :int = copy.deepcopy(self._prepare_for_class(__lowercase , __lowercase)) __UpperCamelCase :Union[str, Any] = model(**__lowercase , noise=__lowercase) __UpperCamelCase :Tuple = outputs_dict[0].numpy() __UpperCamelCase :Union[str, Any] = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords)) , 1E-6) def UpperCamelCase__ ( self) -> Optional[int]: # make the mask reproducible np.random.seed(2) __UpperCamelCase , __UpperCamelCase :str = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase :int = int((config.image_size // config.patch_size) ** 2) __UpperCamelCase :str = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) def prepare_numpy_arrays(__lowercase): __UpperCamelCase :Optional[int] = {} for k, v in inputs_dict.items(): if tf.is_tensor(__lowercase): __UpperCamelCase :Optional[Any] = v.numpy() else: __UpperCamelCase :Optional[int] = np.array(__lowercase) return inputs_np_dict for model_class in self.all_model_classes: __UpperCamelCase :int = model_class(__lowercase) __UpperCamelCase :Tuple = self._prepare_for_class(__lowercase , __lowercase) __UpperCamelCase :Any = prepare_numpy_arrays(__lowercase) __UpperCamelCase :Any = model(__lowercase , noise=__lowercase) __UpperCamelCase :Tuple = model(**__lowercase , noise=__lowercase) self.assert_outputs_same(__lowercase , __lowercase) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> List[Any]: # make masks reproducible np.random.seed(2) __UpperCamelCase :Any = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2) __UpperCamelCase :Optional[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) __UpperCamelCase :Dict = tf.constant(__lowercase) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __UpperCamelCase :Any = tf_noise super().check_pt_tf_models(__lowercase , __lowercase , __lowercase) def UpperCamelCase__ ( self) -> Tuple: # make mask reproducible np.random.seed(2) __UpperCamelCase , __UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase :Optional[int] = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__),) for module_member_name in dir(__lowercase) 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(__lowercase , __lowercase),) if isinstance(__lowercase , __lowercase) and tf.keras.layers.Layer in module_member.__bases__ and getattr(__lowercase , '''_keras_serializable''' , __lowercase) } __UpperCamelCase :Union[str, Any] = int((config.image_size // config.patch_size) ** 2) __UpperCamelCase :List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) __UpperCamelCase :str = tf.convert_to_tensor(__lowercase) inputs_dict.update({'''noise''': noise}) for main_layer_class in tf_main_layer_classes: __UpperCamelCase :Optional[int] = main_layer_class(__lowercase) __UpperCamelCase :Optional[Any] = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype) for name, tensor in inputs_dict.items() } __UpperCamelCase :Dict = tf.keras.Model(__lowercase , outputs=main_layer(__lowercase)) __UpperCamelCase :str = model(__lowercase) with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase :str = os.path.join(__lowercase , '''keras_model.h5''') model.save(__lowercase) __UpperCamelCase :List[Any] = tf.keras.models.load_model( __lowercase , custom_objects={main_layer_class.__name__: main_layer_class}) assert isinstance(__lowercase , tf.keras.Model) __UpperCamelCase :Optional[Any] = model(__lowercase) self.assert_outputs_same(__lowercase , __lowercase) @slow def UpperCamelCase__ ( self) -> Dict: # make mask reproducible np.random.seed(2) __UpperCamelCase , __UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase :Optional[Any] = int((config.image_size // config.patch_size) ** 2) __UpperCamelCase :Any = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) for model_class in self.all_model_classes: __UpperCamelCase :Optional[int] = model_class(__lowercase) __UpperCamelCase :Union[str, Any] = self._prepare_for_class(__lowercase , __lowercase) __UpperCamelCase :Optional[int] = model(__lowercase , noise=__lowercase) if model_class.__name__ == "TFViTMAEModel": __UpperCamelCase :Any = outputs.last_hidden_state.numpy() __UpperCamelCase :Optional[Any] = 0 else: __UpperCamelCase :List[str] = outputs.logits.numpy() __UpperCamelCase :Optional[int] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase , saved_model=__lowercase) __UpperCamelCase :Optional[int] = model_class.from_pretrained(__lowercase) __UpperCamelCase :List[str] = model(__lowercase , noise=__lowercase) if model_class.__name__ == "TFViTMAEModel": __UpperCamelCase :List[Any] = after_outputs['''last_hidden_state'''].numpy() __UpperCamelCase :List[Any] = 0 else: __UpperCamelCase :Any = after_outputs['''logits'''].numpy() __UpperCamelCase :Tuple = 0 __UpperCamelCase :Any = np.amax(np.abs(out_a - out_a)) self.assertLessEqual(__lowercase , 1E-5) def UpperCamelCase__ ( self) -> Union[str, Any]: # make mask reproducible np.random.seed(2) __UpperCamelCase , __UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase :str = int((config.image_size // config.patch_size) ** 2) __UpperCamelCase :Optional[int] = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) for model_class in self.all_model_classes: __UpperCamelCase :Tuple = model_class(__lowercase) __UpperCamelCase :Any = self._prepare_for_class(__lowercase , __lowercase) __UpperCamelCase :Tuple = model(__lowercase , noise=__lowercase) __UpperCamelCase :List[Any] = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(__lowercase) __UpperCamelCase :Optional[Any] = model_class.from_config(model.get_config()) # make sure it also accepts a normal config __UpperCamelCase :Any = model_class.from_config(model.config) __UpperCamelCase :List[Any] = new_model(__lowercase) # Build model new_model.set_weights(model.get_weights()) __UpperCamelCase :str = new_model(__lowercase , noise=__lowercase) self.assert_outputs_same(__lowercase , __lowercase) @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) -> Dict: pass @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load''') def UpperCamelCase__ ( self) -> Any: pass @slow def UpperCamelCase__ ( self) -> Any: __UpperCamelCase :List[Any] = TFViTMAEModel.from_pretrained('''google/vit-base-patch16-224''') self.assertIsNotNone(__lowercase) def lowerCamelCase ( ): '''simple docstring''' __UpperCamelCase :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 UpperCamelCase__ ( self) -> Optional[Any]: return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base''') if is_vision_available() else None @slow def UpperCamelCase__ ( self) -> List[str]: # make random mask reproducible across the PT and TF model np.random.seed(2) __UpperCamelCase :Optional[Any] = TFViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base''') __UpperCamelCase :Optional[int] = self.default_image_processor __UpperCamelCase :Optional[int] = prepare_img() __UpperCamelCase :Optional[int] = image_processor(images=__lowercase , 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) __UpperCamelCase :Union[str, Any] = ViTMAEConfig() __UpperCamelCase :Union[str, Any] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2) __UpperCamelCase :Tuple = np.random.uniform(size=(1, num_patches)) # forward pass __UpperCamelCase :int = model(**__lowercase , noise=__lowercase) # verify the logits __UpperCamelCase :Optional[int] = tf.convert_to_tensor([1, 196, 768]) self.assertEqual(outputs.logits.shape , __lowercase) __UpperCamelCase :List[Any] = tf.convert_to_tensor( [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]]) tf.debugging.assert_near(outputs.logits[0, :3, :3] , __lowercase , atol=1E-4)
43
"""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 _lowercase = NewType('''DataClass''', Any) _lowercase = NewType('''DataClassType''', Any) def _snake_case ( snake_case__ : Tuple ): if isinstance(snake_case__ , snake_case__ ): 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 _snake_case ( snake_case__ : list ): A = {str(snake_case__ ): choice for choice in choices} return lambda snake_case__ : str_to_choice.get(snake_case__ , snake_case__ ) def _snake_case ( *, snake_case__ : Union[str, List[str]] = None , snake_case__ : str = None , snake_case__ : Any = dataclasses.MISSING , snake_case__ : Callable[[], Any] = dataclasses.MISSING , snake_case__ : dict = None , **snake_case__ : Any , ): if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls A = {} if aliases is not None: A = aliases if help is not None: A = help return dataclasses.field(metadata=snake_case__ , default=snake_case__ , default_factory=snake_case__ , **snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Iterable[DataClassType] def __init__( self : List[str] ,A_ : Union[DataClassType, Iterable[DataClassType]] ,**A_ : Any ) -> Optional[int]: # To make the default appear when using --help if "formatter_class" not in kwargs: A = ArgumentDefaultsHelpFormatter super().__init__(**A_ ) if dataclasses.is_dataclass(A_ ): A = [dataclass_types] A = list(A_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ,A_ : dataclasses.Field ) -> Optional[Any]: A = F'--{field.name}' A = 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 ,A_ ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) A = kwargs.pop('aliases' ,[] ) if isinstance(A_ ,A_ ): A = [aliases] A = getattr(field.type ,'__origin__' ,field.type ) if origin_type is Union or (hasattr(A_ ,'UnionType' ) and isinstance(A_ ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A_ ) 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(A_ ) not in field.type.__args__: # filter `str` in Union A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] A = getattr(field.type ,'__origin__' ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) A = ( field.type.__args__[0] if isinstance(A_ ,field.type.__args__[1] ) else field.type.__args__[1] ) A = 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) A = {} if origin_type is Literal or (isinstance(field.type ,A_ ) and issubclass(field.type ,A_ )): if origin_type is Literal: A = field.type.__args__ else: A = [x.value for x in field.type] A = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: A = field.default else: A = 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 A = copy(A_ ) # Hack because type=bool in argparse does not behave as we want. A = 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. A = 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 A = default # This tells argparse we accept 0 or 1 value after --field_name A = '?' # This is the value that will get picked if we do --field_name (without value) A = True elif isclass(A_ ) and issubclass(A_ ,A_ ): A = field.type.__args__[0] A = '+' if field.default_factory is not dataclasses.MISSING: A = field.default_factory() elif field.default is dataclasses.MISSING: A = True else: A = field.type if field.default is not dataclasses.MISSING: A = field.default elif field.default_factory is not dataclasses.MISSING: A = field.default_factory() else: A = True parser.add_argument(A_ ,*A_ ,**A_ ) # 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]): A = False parser.add_argument(F'--no_{field.name}' ,action='store_false' ,dest=field.name ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : DataClassType ) -> List[Any]: if hasattr(A_ ,'_argument_group_name' ): A = self.add_argument_group(dtype._argument_group_name ) else: A = self try: A = get_type_hints(A_ ) 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(A_ ): A = '.'.join(map(A_ ,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(A_ ): if not field.init: continue A = type_hints[field.name] self._parse_dataclass_field(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Any=None ,A_ : int=False ,A_ : Any=True ,A_ : List[str]=None ,A_ : Union[str, Any]=None ,) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): A = [] if args_filename: args_files.append(Path(A_ ) ) 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 A = ArgumentParser() args_file_parser.add_argument(A_ ,type=A_ ,action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) A , A = args_file_parser.parse_known_args(args=A_ ) A = vars(A_ ).get(args_file_flag.lstrip('-' ) ,A_ ) if cmd_args_file_paths: args_files.extend([Path(A_ ) for p in cmd_args_file_paths] ) A = [] 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 A = file_args + args if args is not None else file_args + sys.argv[1:] A , A = self.parse_known_args(args=A_ ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in vars(A_ ).items() if k in keys} for k in keys: delattr(A_ ,A_ ) A = dtype(**A_ ) outputs.append(A_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A_ ) 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 _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Dict[str, Any] ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = set(args.keys() ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) A = dtype(**A_ ) outputs.append(A_ ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(A_ )}' ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: with open(Path(A_ ) ,encoding='utf-8' ) as open_json_file: A = json.loads(open_json_file.read() ) A = self.parse_dict(A_ ,allow_extra_keys=A_ ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = self.parse_dict(yaml.safe_load(Path(A_ ).read_text() ) ,allow_extra_keys=A_ ) return tuple(A_ )
74
0
"""simple docstring""" import enum import shutil import sys _a , _a : int = shutil.get_terminal_size() _a : Optional[Any] = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class __A ( enum.Enum ): _UpperCamelCase : int = 0 _UpperCamelCase : List[str] = 1 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : Tuple="" ) -> Optional[int]: sys.stdout.write(str(_lowerCamelCase ) + end ) sys.stdout.flush() def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : str ,_lowerCamelCase : Union[str, Any]="" ) -> Optional[int]: forceWrite(f"\u001b[{color}m{content}\u001b[0m" ,_lowerCamelCase ) def SCREAMING_SNAKE_CASE ( ) -> int: forceWrite("""\r""" ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : int ,_lowerCamelCase : str ) -> Optional[Any]: forceWrite(f"\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}" ) def SCREAMING_SNAKE_CASE ( ) -> List[Any]: forceWrite(""" """ * TERMINAL_WIDTH ) reset_cursor() def SCREAMING_SNAKE_CASE ( ) -> Any: reset_cursor() forceWrite("""-""" * TERMINAL_WIDTH )
44
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Dict ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : int ): # 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(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Optional[int] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
74
0
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
0
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "microsoft/conditional-detr-resnet-50": ( "https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json" ), } class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = 'conditional_detr' _SCREAMING_SNAKE_CASE = ['past_key_values'] _SCREAMING_SNAKE_CASE = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self , lowercase=True , lowercase=None , lowercase=3 , lowercase=300 , lowercase=6 , lowercase=2_048 , lowercase=8 , lowercase=6 , lowercase=2_048 , lowercase=8 , lowercase=0.0 , lowercase=0.0 , lowercase=True , lowercase="relu" , lowercase=256 , lowercase=0.1 , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=1.0 , lowercase=False , lowercase="sine" , lowercase="resnet50" , lowercase=True , lowercase=False , lowercase=2 , lowercase=5 , lowercase=2 , lowercase=1 , lowercase=1 , lowercase=2 , lowercase=5 , lowercase=2 , lowercase=0.25 , **lowercase , ) -> str: if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCAmelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(lowercase , lowercase ): lowerCAmelCase = backbone_config.get("""model_type""" ) lowerCAmelCase = CONFIG_MAPPING[backbone_model_type] lowerCAmelCase = config_class.from_dict(lowercase ) lowerCAmelCase = use_timm_backbone lowerCAmelCase = backbone_config lowerCAmelCase = num_channels lowerCAmelCase = num_queries lowerCAmelCase = d_model lowerCAmelCase = encoder_ffn_dim lowerCAmelCase = encoder_layers lowerCAmelCase = encoder_attention_heads lowerCAmelCase = decoder_ffn_dim lowerCAmelCase = decoder_layers lowerCAmelCase = decoder_attention_heads lowerCAmelCase = dropout lowerCAmelCase = attention_dropout lowerCAmelCase = activation_dropout lowerCAmelCase = activation_function lowerCAmelCase = init_std lowerCAmelCase = init_xavier_std lowerCAmelCase = encoder_layerdrop lowerCAmelCase = decoder_layerdrop lowerCAmelCase = encoder_layers lowerCAmelCase = auxiliary_loss lowerCAmelCase = position_embedding_type lowerCAmelCase = backbone lowerCAmelCase = use_pretrained_backbone lowerCAmelCase = dilation # Hungarian matcher lowerCAmelCase = class_cost lowerCAmelCase = bbox_cost lowerCAmelCase = giou_cost # Loss coefficients lowerCAmelCase = mask_loss_coefficient lowerCAmelCase = dice_loss_coefficient lowerCAmelCase = cls_loss_coefficient lowerCAmelCase = bbox_loss_coefficient lowerCAmelCase = giou_loss_coefficient lowerCAmelCase = focal_alpha super().__init__(is_encoder_decoder=lowercase , **lowercase ) @property def _snake_case ( self ) -> int: return self.encoder_attention_heads @property def _snake_case ( self ) -> int: return self.d_model def _snake_case ( self ) -> Optional[Any]: lowerCAmelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: lowerCAmelCase = self.backbone_config.to_dict() lowerCAmelCase = self.__class__.model_type return output class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = version.parse('1.11' ) @property def _snake_case ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def _snake_case ( self ) -> float: return 1e-5 @property def _snake_case ( self ) -> int: return 12
46
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase = logging.get_logger(__name__) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : int ,**A_ : Any ) -> Any: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A = deprecated_arg[3:] A = not kwargs.pop(A_ ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) A = kwargs.pop('tpu_name' ,self.tpu_name ) A = kwargs.pop('device_idx' ,self.device_idx ) A = kwargs.pop('eager_mode' ,self.eager_mode ) A = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**A_ ) _lowerCamelCase: str = field( default=_lowercase , metadata={'''help''': '''Name of TPU'''} , ) _lowerCamelCase: int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) _lowerCamelCase: bool = field(default=_lowercase , metadata={'''help''': '''Benchmark models in eager model.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) A = None if self.tpu: try: if self.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: A = None return tpu @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) A = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) A = tf.distribute.OneDeviceStrategy(device=F'/gpu:{self.device_idx}' ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU A = tf.distribute.OneDeviceStrategy(device=F'/cpu:{self.device_idx}' ) return strategy @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def _SCREAMING_SNAKE_CASE ( self : int ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _SCREAMING_SNAKE_CASE ( self : str ) -> bool: return self.n_gpu > 0
74
0
'''simple docstring''' import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem lowerCamelCase : Union[str, Any] = importlib.util.find_spec("s3fs") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 lowerCamelCase : List[compression.BaseCompressedFileFileSystem] = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(f'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def _lowerCAmelCase ( _UpperCamelCase : str ) -> str: """simple docstring""" if "://" in dataset_path: _SCREAMING_SNAKE_CASE =dataset_path.split('://' )[1] return dataset_path def _lowerCAmelCase ( _UpperCamelCase : fsspec.AbstractFileSystem ) -> bool: """simple docstring""" if fs is not None and fs.protocol != "file": return True else: return False def _lowerCAmelCase ( _UpperCamelCase : fsspec.AbstractFileSystem , _UpperCamelCase : str , _UpperCamelCase : str ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =not is_remote_filesystem(_UpperCamelCase ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_UpperCamelCase ) , fs._strip_protocol(_UpperCamelCase ) ) else: fs.mv(_UpperCamelCase , _UpperCamelCase , recursive=_UpperCamelCase ) def _lowerCAmelCase ( ) -> None: """simple docstring""" if hasattr(fsspec.asyn , 'reset_lock' ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =threading.Lock()
47
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowercase = logging.get_logger(__name__) _lowercase = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''dpt''' def __init__( self : str ,A_ : Tuple=768 ,A_ : int=12 ,A_ : Optional[int]=12 ,A_ : Optional[int]=3072 ,A_ : List[str]="gelu" ,A_ : str=0.0 ,A_ : int=0.0 ,A_ : str=0.02 ,A_ : str=1e-12 ,A_ : str=384 ,A_ : Dict=16 ,A_ : Union[str, Any]=3 ,A_ : Dict=False ,A_ : Any=True ,A_ : Optional[int]=[2, 5, 8, 11] ,A_ : Optional[Any]="project" ,A_ : Tuple=[4, 2, 1, 0.5] ,A_ : int=[96, 192, 384, 768] ,A_ : int=256 ,A_ : str=-1 ,A_ : Optional[int]=False ,A_ : Optional[int]=True ,A_ : Union[str, Any]=0.4 ,A_ : Union[str, Any]=255 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=[1, 1024, 24, 24] ,A_ : List[str]=[0, 1] ,A_ : List[Any]=None ,**A_ : Tuple ,) -> Union[str, Any]: super().__init__(**A_ ) A = hidden_size A = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): logger.info('Initializing the config with a `BiT` backbone.' ) A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): A = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) A = backbone_featmap_shape A = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: A = None A = None A = [] A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) A = readout_type A = reassemble_factors A = neck_hidden_sizes A = fusion_hidden_size A = head_in_index A = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) A = use_auxiliary_head A = auxiliary_loss_weight A = semantic_loss_ignore_index A = semantic_classifier_dropout def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: A = self.backbone_config.to_dict() A = self.__class__.model_type return output
74
0
import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' lowerCamelCase_ : Optional[Any] = MODEL_FOR_MASKED_LM_MAPPING lowerCamelCase_ : List[Any] = TF_MODEL_FOR_MASKED_LM_MAPPING def _lowercase ( self ) -> List[Any]: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def _lowercase ( self ) -> List[str]: lowerCamelCase : str = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="tf" ) lowerCamelCase : Dict = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"sequence": "My name is grouped", "score": 2.1e-05, "token": 3_8015, "token_str": " grouped"}, {"sequence": "My name is accuser", "score": 2.1e-05, "token": 2_5506, "token_str": " accuser"}, ] , ) lowerCamelCase : int = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ { "sequence": "The largest city in France is grouped", "score": 2.1e-05, "token": 3_8015, "token_str": " grouped", }, { "sequence": "The largest city in France is accuser", "score": 2.1e-05, "token": 2_5506, "token_str": " accuser", }, ] , ) lowerCamelCase : List[str] = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"sequence": "My name is Clara", "score": 2e-05, "token": 1_3606, "token_str": " Clara"}, {"sequence": "My name is Patrick", "score": 2e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 1.9e-05, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _lowercase ( self ) -> List[str]: lowerCamelCase : List[Any] = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="pt" ) lowerCamelCase : Tuple = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"sequence": "My name is Maul", "score": 2.2e-05, "token": 3_5676, "token_str": " Maul"}, {"sequence": "My name isELS", "score": 2.2e-05, "token": 1_6416, "token_str": "ELS"}, ] , ) lowerCamelCase : Union[str, Any] = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ { "sequence": "The largest city in France is Maul", "score": 2.2e-05, "token": 3_5676, "token_str": " Maul", }, {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 1_6416, "token_str": "ELS"}, ] , ) lowerCamelCase : int = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"}, {"sequence": "My name is Clara", "score": 2e-05, "token": 1_3606, "token_str": " Clara"}, ] , ) lowerCamelCase : int = unmasker("My name is <mask> <mask>" , top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ [ { "score": 2.2e-05, "token": 3_5676, "token_str": " Maul", "sequence": "<s>My name is Maul<mask></s>", }, {"score": 2.2e-05, "token": 1_6416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"}, ], [ { "score": 2.2e-05, "token": 3_5676, "token_str": " Maul", "sequence": "<s>My name is<mask> Maul</s>", }, {"score": 2.2e-05, "token": 1_6416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"}, ], ] , ) @require_torch_gpu def _lowercase ( self ) -> Dict: lowerCamelCase : Any = pipeline("fill-mask" , model="hf-internal-testing/tiny-random-distilbert" , device=0 , framework="pt" ) # convert model to fp16 pipe.model.half() lowerCamelCase : Tuple = pipe("Paris is the [MASK] of France." ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) @slow @require_torch def _lowercase ( self ) -> List[Any]: lowerCamelCase : Tuple = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="pt" ) self.run_large_test(UpperCamelCase__ ) @slow @require_tf def _lowercase ( self ) -> str: lowerCamelCase : Tuple = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="tf" ) self.run_large_test(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ ) -> Optional[int]: lowerCamelCase : List[Any] = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, {"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"}, ] , ) lowerCamelCase : List[Any] = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ { "sequence": "The largest city in France is Paris", "score": 0.251, "token": 2201, "token_str": " Paris", }, { "sequence": "The largest city in France is Lyon", "score": 0.214, "token": 1_2790, "token_str": " Lyon", }, ] , ) lowerCamelCase : int = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ {"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Clara", "score": 0.000, "token": 1_3606, "token_str": " Clara"}, {"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _lowercase ( self ) -> List[str]: lowerCamelCase : Union[str, Any] = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="pt" ) lowerCamelCase : List[str] = None lowerCamelCase : Dict = None self.run_pipeline_test(UpperCamelCase__ , [] ) @require_tf def _lowercase ( self ) -> Optional[Any]: lowerCamelCase : Optional[int] = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="tf" ) lowerCamelCase : int = None lowerCamelCase : List[Any] = None self.run_pipeline_test(UpperCamelCase__ , [] ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)" ) lowerCamelCase : Union[str, Any] = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = [ F'''This is another {tokenizer.mask_token} test''', ] return fill_masker, examples def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> int: lowerCamelCase : Tuple = fill_masker.tokenizer lowerCamelCase : Optional[Any] = fill_masker.model lowerCamelCase : Optional[int] = fill_masker( F'''This is a {tokenizer.mask_token}''' , ) self.assertEqual( UpperCamelCase__ , [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase : int = fill_masker([F'''This is a {tokenizer.mask_token}'''] ) self.assertEqual( UpperCamelCase__ , [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase : Any = fill_masker([F'''This is a {tokenizer.mask_token}''', F'''Another {tokenizer.mask_token} great test.'''] ) self.assertEqual( UpperCamelCase__ , [ [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ], [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ], ] , ) with self.assertRaises(UpperCamelCase__ ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(UpperCamelCase__ ): fill_masker("This is" ) self.run_test_top_k(UpperCamelCase__ , UpperCamelCase__ ) self.run_test_targets(UpperCamelCase__ , UpperCamelCase__ ) self.run_test_top_k_targets(UpperCamelCase__ , UpperCamelCase__ ) self.fill_mask_with_duplicate_targets_and_top_k(UpperCamelCase__ , UpperCamelCase__ ) self.fill_mask_with_multiple_masks(UpperCamelCase__ , UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Any: lowerCamelCase : Dict = tokenizer.get_vocab() lowerCamelCase : Tuple = sorted(vocab.keys() )[:2] # Pipeline argument lowerCamelCase : int = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ , targets=UpperCamelCase__ ) lowerCamelCase : List[Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' ) self.assertEqual( UpperCamelCase__ , [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase : List[str] = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , UpperCamelCase__ ) lowerCamelCase : Any = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(UpperCamelCase__ ) ) # Call argument lowerCamelCase : Tuple = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase : Tuple = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase : List[str] = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , UpperCamelCase__ ) lowerCamelCase : List[str] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(UpperCamelCase__ ) ) # Score equivalence lowerCamelCase : Optional[Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = [top_mask["token_str"] for top_mask in outputs] lowerCamelCase : Union[str, Any] = [top_mask["score"] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCamelCase__ ) == set(UpperCamelCase__ ): lowerCamelCase : Any = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase__ ) lowerCamelCase : List[str] = [top_mask["score"] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(UpperCamelCase__ ) , nested_simplify(UpperCamelCase__ ) ) # Raises with invalid with self.assertRaises(UpperCamelCase__ ): lowerCamelCase : Any = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(UpperCamelCase__ ): lowerCamelCase : int = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=[""] ) with self.assertRaises(UpperCamelCase__ ): lowerCamelCase : int = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets="" ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: lowerCamelCase : Union[str, Any] = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ , top_k=2 ) lowerCamelCase : Union[str, Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' ) self.assertEqual( UpperCamelCase__ , [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase : Union[str, Any] = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase : int = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2 ) self.assertEqual( UpperCamelCase__ , [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ] , ) self.assertEqual(nested_simplify(UpperCamelCase__ ) , nested_simplify(UpperCamelCase__ ) ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> int: lowerCamelCase : Tuple = tokenizer.get_vocab() lowerCamelCase : Any = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # top_k=2, ntargets=3 lowerCamelCase : Any = sorted(vocab.keys() )[:3] lowerCamelCase : Dict = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2 , targets=UpperCamelCase__ ) # If we use the most probably targets, and filter differently, we should still # have the same results lowerCamelCase : List[Any] = [el["token_str"] for el in sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : x["score"] , reverse=UpperCamelCase__ )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCamelCase__ ).issubset(UpperCamelCase__ ): lowerCamelCase : int = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=3 , targets=UpperCamelCase__ ) # They should yield exactly the same result self.assertEqual(nested_simplify(UpperCamelCase__ ) , nested_simplify(UpperCamelCase__ ) ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> str: lowerCamelCase : int = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase : str = tokenizer.get_vocab() # String duplicates + id duplicates lowerCamelCase : Tuple = sorted(vocab.keys() )[:3] lowerCamelCase : List[str] = [targets[0], targets[1], targets[0], targets[2], targets[1]] lowerCamelCase : int = fill_masker(F'''My name is {tokenizer.mask_token}''' , targets=UpperCamelCase__ , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(UpperCamelCase__ ) , 3 ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Dict: lowerCamelCase : int = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase : Tuple = fill_masker( F'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}''' , top_k=2 ) self.assertEqual( UpperCamelCase__ , [ [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ], [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ], [ {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, {"sequence": ANY(UpperCamelCase__ ), "score": ANY(UpperCamelCase__ ), "token": ANY(UpperCamelCase__ ), "token_str": ANY(UpperCamelCase__ )}, ], ] , )
48
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __snake_case :str = {'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case :List[Any] = ['''YolosFeatureExtractor'''] __snake_case :Optional[Any] = ['''YolosImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case :List[str] = [ '''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''YolosForObjectDetection''', '''YolosModel''', '''YolosPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys __snake_case :Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
49
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ,A_ : int ) -> Union[str, Any]: A = n A = [None] * self.n A = 0 # index of the first element A = 0 A = 0 def __len__( self : int ) -> int: return self.size def _SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.size == 0 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: return False if self.is_empty() else self.array[self.front] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ) -> int: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A = data A = (self.rear + 1) % self.n self.size += 1 return self def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) A = self.array[self.front] A = None A = (self.front + 1) % self.n self.size -= 1 return temp
74
0
from __future__ import annotations _UpperCAmelCase : Optional[int] = tuple[int, int, int] _UpperCAmelCase : int = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase _UpperCAmelCase : Optional[int] = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- _UpperCAmelCase : List[str] = """EGZWVONAHDCLFQMSIPJBYUKXTR""" _UpperCAmelCase : Optional[int] = """FOBHMDKEXQNRAULPGSJVTYICZW""" _UpperCAmelCase : List[Any] = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- _UpperCAmelCase : Union[str, Any] = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- _UpperCAmelCase : List[str] = """RMDJXFUWGISLHVTCQNKYPBEZOA""" _UpperCAmelCase : Any = """SGLCPQWZHKXAREONTFBVIYJUDM""" _UpperCAmelCase : List[str] = """HVSICLTYKQUBXDWAJZOMFGPREN""" _UpperCAmelCase : Tuple = """RZWQHFMVDBKICJLNTUXAGYPSOE""" _UpperCAmelCase : Optional[int] = """LFKIJODBEGAMQPXVUHYSTCZRWN""" _UpperCAmelCase : Tuple = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(_UpperCAmelCase ) )) < 3: lowerCamelCase__ : int = F"""Please use 3 unique rotors (not {unique_rotsel})""" raise Exception(_UpperCAmelCase ) # Checks if rotor positions are valid lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = rotpos if not 0 < rotorposa <= len(_UpperCAmelCase ): lowerCamelCase__ : List[Any] = F"""First rotor position is not within range of 1..26 ({rotorposa}""" raise ValueError(_UpperCAmelCase ) if not 0 < rotorposa <= len(_UpperCAmelCase ): lowerCamelCase__ : List[Any] = F"""Second rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(_UpperCAmelCase ) if not 0 < rotorposa <= len(_UpperCAmelCase ): lowerCamelCase__ : int = F"""Third rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(_UpperCAmelCase ) # Validates string and returns dict lowerCamelCase__ : Optional[int] = _plugboard(_UpperCAmelCase ) return rotpos, rotsel, pbdict def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> dict[str, str]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowerCamelCase__ : Union[str, Any] = F"""Plugboard setting isn't type string ({type(_UpperCAmelCase )})""" raise TypeError(_UpperCAmelCase ) elif len(_UpperCAmelCase ) % 2 != 0: lowerCamelCase__ : Dict = F"""Odd number of symbols ({len(_UpperCAmelCase )})""" raise Exception(_UpperCAmelCase ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique lowerCamelCase__ : Dict = set() for i in pbstring: if i not in abc: lowerCamelCase__ : Union[str, Any] = F"""'{i}' not in list of symbols""" raise Exception(_UpperCAmelCase ) elif i in tmppbl: lowerCamelCase__ : Optional[Any] = F"""Duplicate symbol ({i})""" raise Exception(_UpperCAmelCase ) else: tmppbl.add(_UpperCAmelCase ) del tmppbl # Created the dictionary lowerCamelCase__ : Dict = {} for j in range(0 , len(_UpperCAmelCase ) - 1 , 2 ): lowerCamelCase__ : int = pbstring[j + 1] lowerCamelCase__ : Union[str, Any] = pbstring[j] return pb def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = (rotora, rotora, rotora) , _UpperCAmelCase = "" , ) -> str: lowerCamelCase__ : List[Any] = text.upper() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = _validator( _UpperCAmelCase , _UpperCAmelCase , plugb.upper() ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Tuple = rotor_position lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 lowerCamelCase__ : Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: lowerCamelCase__ : Tuple = plugboard[symbol] # rotor ra -------------------------- lowerCamelCase__ : Optional[Any] = abc.index(_UpperCAmelCase ) + rotorposa lowerCamelCase__ : int = rotora[index % len(_UpperCAmelCase )] # rotor rb -------------------------- lowerCamelCase__ : Dict = abc.index(_UpperCAmelCase ) + rotorposa lowerCamelCase__ : Optional[Any] = rotora[index % len(_UpperCAmelCase )] # rotor rc -------------------------- lowerCamelCase__ : str = abc.index(_UpperCAmelCase ) + rotorposa lowerCamelCase__ : Optional[Any] = rotora[index % len(_UpperCAmelCase )] # reflector -------------------------- # this is the reason you don't need another machine to decipher lowerCamelCase__ : List[Any] = reflector[symbol] # 2nd rotors lowerCamelCase__ : Union[str, Any] = abc[rotora.index(_UpperCAmelCase ) - rotorposa] lowerCamelCase__ : Tuple = abc[rotora.index(_UpperCAmelCase ) - rotorposa] lowerCamelCase__ : str = abc[rotora.index(_UpperCAmelCase ) - rotorposa] # 2nd plugboard if symbol in plugboard: lowerCamelCase__ : Dict = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_UpperCAmelCase ): lowerCamelCase__ : Optional[Any] = 0 rotorposa += 1 if rotorposa >= len(_UpperCAmelCase ): lowerCamelCase__ : Optional[Any] = 0 rotorposa += 1 if rotorposa >= len(_UpperCAmelCase ): lowerCamelCase__ : Union[str, Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_UpperCAmelCase ) return "".join(_UpperCAmelCase ) if __name__ == "__main__": _UpperCAmelCase : Optional[int] = """This is my Python script that emulates the Enigma machine from WWII.""" _UpperCAmelCase : List[Any] = (1, 1, 1) _UpperCAmelCase : List[Any] = """pictures""" _UpperCAmelCase : int = (rotora, rotora, rotora) _UpperCAmelCase : Any = enigma(message, rotor_pos, rotor_sel, pb) print("""Encrypted message:""", en) print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
50
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,*A_ : List[str] ,**A_ : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' ,A_ ,) super().__init__(*A_ ,**A_ )
74
0
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __snake_case ( a ): UpperCAmelCase__ : UNetaDModel UpperCAmelCase__ : ScoreSdeVeScheduler def __init__( self : Any , _snake_case : UNetaDModel , _snake_case : ScoreSdeVeScheduler): """simple docstring""" super().__init__() self.register_modules(unet=_snake_case , scheduler=_snake_case) @torch.no_grad() def __call__( self : Union[str, Any] , _snake_case : int = 1 , _snake_case : int = 2000 , _snake_case : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _snake_case : Optional[str] = "pil" , _snake_case : bool = True , **_snake_case : Tuple , ): """simple docstring""" UpperCAmelCase_ = self.unet.config.sample_size UpperCAmelCase_ = (batch_size, 3, img_size, img_size) UpperCAmelCase_ = self.unet UpperCAmelCase_ = randn_tensor(_snake_case , generator=_snake_case) * self.scheduler.init_noise_sigma UpperCAmelCase_ = sample.to(self.device) self.scheduler.set_timesteps(_snake_case) self.scheduler.set_sigmas(_snake_case) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)): UpperCAmelCase_ = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device) # correction step for _ in range(self.scheduler.config.correct_steps): UpperCAmelCase_ = self.unet(_snake_case , _snake_case).sample UpperCAmelCase_ = self.scheduler.step_correct(_snake_case , _snake_case , generator=_snake_case).prev_sample # prediction step UpperCAmelCase_ = model(_snake_case , _snake_case).sample UpperCAmelCase_ = self.scheduler.step_pred(_snake_case , _snake_case , _snake_case , generator=_snake_case) UpperCAmelCase_ , UpperCAmelCase_ = output.prev_sample, output.prev_sample_mean UpperCAmelCase_ = sample_mean.clamp(0 , 1) UpperCAmelCase_ = sample.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": UpperCAmelCase_ = self.numpy_to_pil(_snake_case) if not return_dict: return (sample,) return ImagePipelineOutput(images=_snake_case)
51
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''gpt_bigcode''' _lowerCamelCase: List[Any] = ['''past_key_values'''] _lowerCamelCase: int = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Optional[int] ,A_ : Dict=5_0257 ,A_ : Union[str, Any]=1024 ,A_ : str=768 ,A_ : Any=12 ,A_ : Any=12 ,A_ : Optional[int]=None ,A_ : Any="gelu_pytorch_tanh" ,A_ : List[str]=0.1 ,A_ : Optional[int]=0.1 ,A_ : List[str]=0.1 ,A_ : Tuple=1e-5 ,A_ : Optional[int]=0.02 ,A_ : List[str]=True ,A_ : Optional[Any]=True ,A_ : List[Any]=5_0256 ,A_ : Union[str, Any]=5_0256 ,A_ : int=True ,A_ : Optional[Any]=True ,A_ : Dict=True ,**A_ : Union[str, Any] ,) -> Union[str, Any]: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = scale_attn_weights A = use_cache A = attention_softmax_in_fpaa A = scale_attention_softmax_in_fpaa A = multi_query A = bos_token_id A = eos_token_id super().__init__(bos_token_id=A_ ,eos_token_id=A_ ,**A_ )
74
0
import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=True , A_=False , A_=False , A_=False , A_=2 , A_=99 , A_=0 , A_=32 , A_=5 , A_=4 , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=2 , A_=4 , A_="last" , A_=True , A_=None , A_=0 , ): '''simple docstring''' UpperCamelCase : Any = parent UpperCamelCase : str = batch_size UpperCamelCase : Tuple = seq_length UpperCamelCase : Union[str, Any] = is_training UpperCamelCase : List[Any] = use_input_lengths UpperCamelCase : Optional[Any] = use_token_type_ids UpperCamelCase : Optional[int] = use_labels UpperCamelCase : Optional[int] = gelu_activation UpperCamelCase : Optional[Any] = sinusoidal_embeddings UpperCamelCase : Tuple = causal UpperCamelCase : List[Any] = asm UpperCamelCase : List[str] = n_langs UpperCamelCase : Any = vocab_size UpperCamelCase : List[str] = n_special UpperCamelCase : Optional[Any] = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[int] = hidden_dropout_prob UpperCamelCase : Optional[Any] = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Union[str, Any] = type_sequence_label_size UpperCamelCase : Optional[int] = initializer_range UpperCamelCase : Any = num_labels UpperCamelCase : Dict = num_choices UpperCamelCase : Union[str, Any] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[Any] = scope UpperCamelCase : List[Any] = bos_token_id def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : int = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : List[str] = None if self.use_input_lengths: UpperCamelCase : Optional[int] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Optional[int] = None if self.use_token_type_ids: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : Dict = None UpperCamelCase : int = None UpperCamelCase : Union[str, Any] = None if self.use_labels: UpperCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Optional[int] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __UpperCamelCase( self ): '''simple docstring''' return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : List[str] = XLMModel(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Optional[int] = model(A_ , lengths=A_ , langs=A_ ) UpperCamelCase : Optional[int] = model(A_ , langs=A_ ) UpperCamelCase : Any = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[Any] = model(A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() UpperCamelCase : str = model(A_ ) UpperCamelCase : List[Any] = model(A_ , start_positions=A_ , end_positions=A_ ) UpperCamelCase : Optional[Any] = outputs 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_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Optional[Any] = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() UpperCamelCase : Tuple = model(A_ ) UpperCamelCase : int = model( A_ , start_positions=A_ , end_positions=A_ , cls_index=A_ , is_impossible=A_ , p_mask=A_ , ) UpperCamelCase : Dict = model( A_ , start_positions=A_ , end_positions=A_ , cls_index=A_ , is_impossible=A_ , ) ((UpperCamelCase) , ) : List[Any] = result_with_labels.to_tuple() UpperCamelCase : Tuple = model(A_ , start_positions=A_ , end_positions=A_ ) ((UpperCamelCase) , ) : Any = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Any = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() UpperCamelCase : Any = model(A_ ) UpperCamelCase : str = model(A_ , labels=A_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : List[str] = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() UpperCamelCase : Optional[int] = model(A_ , attention_mask=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): '''simple docstring''' UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[int] = model( A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[Any] = config_and_inputs UpperCamelCase : Tuple = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} return config, inputs_dict @require_torch class A__ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :int = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _UpperCAmelCase :Optional[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _UpperCAmelCase :Union[str, Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __UpperCamelCase( self , A_ , A_ , A_=False ): '''simple docstring''' UpperCamelCase : Union[str, Any] = super()._prepare_for_class(A_ , A_ , return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A_ ) UpperCamelCase : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A_ ) return inputs_dict def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = XLMModelTester(self ) UpperCamelCase : Any = ConfigTester(self , config_class=A_ , emb_dim=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_=False , A_=1 ): '''simple docstring''' self.assertIsInstance(A_ , A_ ) self.assertListEqual( [isinstance(A_ , A_ ) for iter_attentions in attentions] , [True] * len(A_ ) ) self.assertEqual(len(A_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token UpperCamelCase : str = min_length + idx + 1 UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : str = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(A_ ) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_=False , A_=1 ): '''simple docstring''' self.assertIsInstance(A_ , A_ ) self.assertListEqual( [isinstance(A_ , A_ ) for iter_hidden_states in hidden_states] , [True] * len(A_ ) , ) self.assertEqual(len(A_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token UpperCamelCase : Any = min_length + idx + 1 UpperCamelCase : Optional[int] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(A_ ) , ) pass @slow def __UpperCamelCase( self ): '''simple docstring''' for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class A__ ( unittest.TestCase ): @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048" ) model.to(A_ ) UpperCamelCase : Dict = torch.tensor([[14, 447]] , dtype=torch.long , device=A_ ) # the president UpperCamelCase : int = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(A_ , do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , A_ )
52
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
0
'''simple docstring''' from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function a__ : Any =1.054571817E-34 # unit of ℏ : J * s a__ : List[Any] =3E8 # unit of c : m * s^-1 def lowercase__ ( __lowercase : float , __lowercase : float , __lowercase : float ) -> dict[str, float]: """simple docstring""" if (force, area, distance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if force < 0: raise ValueError('Magnitude of force can not be negative' ) if distance < 0: raise ValueError('Distance can not be negative' ) if area < 0: raise ValueError('Area can not be negative' ) if force == 0: __UpperCamelCase = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: __UpperCamelCase = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: __UpperCamelCase = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('One and only one argument must be 0' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
53
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
0
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput a__ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" @register_to_config def __init__( self : Tuple , UpperCAmelCase__ : bool , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None ) -> Tuple: super().__init__() __SCREAMING_SNAKE_CASE = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" __SCREAMING_SNAKE_CASE = torch.zeros(UpperCAmelCase__ , UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = torch.nn.Parameter(UpperCAmelCase__ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : VQModel snake_case__ : CLIPTextModel snake_case__ : CLIPTokenizer snake_case__ : TransformeraDModel snake_case__ : LearnedClassifierFreeSamplingEmbeddings snake_case__ : VQDiffusionScheduler def __init__( self : Union[str, Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : CLIPTextModel , UpperCAmelCase__ : CLIPTokenizer , UpperCAmelCase__ : TransformeraDModel , UpperCAmelCase__ : VQDiffusionScheduler , UpperCAmelCase__ : LearnedClassifierFreeSamplingEmbeddings , ) -> int: super().__init__() self.register_modules( vqvae=UpperCAmelCase__ , transformer=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , learned_classifier_free_sampling_embeddings=UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ) -> int: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else 1 # get prompt text embeddings __SCREAMING_SNAKE_CASE = self.tokenizer( UpperCAmelCase__ , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) __SCREAMING_SNAKE_CASE = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" F""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) __SCREAMING_SNAKE_CASE = text_input_ids[:, : self.tokenizer.model_max_length] __SCREAMING_SNAKE_CASE = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 __SCREAMING_SNAKE_CASE = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase__ ) # duplicate text embeddings for each generation per prompt __SCREAMING_SNAKE_CASE = prompt_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: __SCREAMING_SNAKE_CASE = self.learned_classifier_free_sampling_embeddings.embeddings __SCREAMING_SNAKE_CASE = negative_prompt_embeds.unsqueeze(0 ).repeat(UpperCAmelCase__ , 1 , 1 ) else: __SCREAMING_SNAKE_CASE = [""] * batch_size __SCREAMING_SNAKE_CASE = text_input_ids.shape[-1] __SCREAMING_SNAKE_CASE = self.tokenizer( UpperCAmelCase__ , padding="max_length" , max_length=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors="pt" , ) __SCREAMING_SNAKE_CASE = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings __SCREAMING_SNAKE_CASE = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase__ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __SCREAMING_SNAKE_CASE = negative_prompt_embeds.shape[1] __SCREAMING_SNAKE_CASE = negative_prompt_embeds.repeat(1 , UpperCAmelCase__ , 1 ) __SCREAMING_SNAKE_CASE = negative_prompt_embeds.view(batch_size * num_images_per_prompt , UpperCAmelCase__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __SCREAMING_SNAKE_CASE = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : Tuple , UpperCAmelCase__ : Union[str, List[str]] , UpperCAmelCase__ : int = 1_0_0 , UpperCAmelCase__ : float = 5.0 , UpperCAmelCase__ : float = 1.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase__ : int = 1 , ) -> Union[ImagePipelineOutput, Tuple]: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = 1 elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase__ )}""" ) __SCREAMING_SNAKE_CASE = batch_size * num_images_per_prompt __SCREAMING_SNAKE_CASE = guidance_scale > 1.0 __SCREAMING_SNAKE_CASE = self._encode_prompt(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(UpperCAmelCase__ )}.""" ) # get the initial completely masked latents unless the user supplied it __SCREAMING_SNAKE_CASE = (batch_size, self.transformer.num_latent_pixels) if latents is None: __SCREAMING_SNAKE_CASE = self.transformer.num_vector_embeds - 1 __SCREAMING_SNAKE_CASE = torch.full(UpperCAmelCase__ , UpperCAmelCase__ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( "Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0," F""" {self.transformer.num_vector_embeds - 1} (inclusive).""" ) __SCREAMING_SNAKE_CASE = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) __SCREAMING_SNAKE_CASE = self.scheduler.timesteps.to(self.device ) __SCREAMING_SNAKE_CASE = latents for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the sample if we are doing classifier free guidance __SCREAMING_SNAKE_CASE = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` __SCREAMING_SNAKE_CASE = self.transformer(UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , timestep=UpperCAmelCase__ ).sample if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_output.chunk(2 ) __SCREAMING_SNAKE_CASE = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(UpperCAmelCase__ , dim=1 , keepdim=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.truncate(UpperCAmelCase__ , UpperCAmelCase__ ) # remove `log(0)`'s (`-inf`s) __SCREAMING_SNAKE_CASE = model_output.clamp(-7_0 ) # compute the previous noisy sample x_t -> x_t-1 __SCREAMING_SNAKE_CASE = self.scheduler.step(UpperCAmelCase__ , timestep=UpperCAmelCase__ , sample=UpperCAmelCase__ , generator=UpperCAmelCase__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.vqvae.config.vq_embed_dim __SCREAMING_SNAKE_CASE = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) __SCREAMING_SNAKE_CASE = self.vqvae.quantize.get_codebook_entry(UpperCAmelCase__ , shape=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.vqvae.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = (image / 2 + 0.5).clamp(0 , 1 ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : torch.FloatTensor , UpperCAmelCase__ : float ) -> torch.FloatTensor: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = torch.sort(UpperCAmelCase__ , 1 , descending=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.exp(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out __SCREAMING_SNAKE_CASE = torch.full_like(keep_mask[:, 0:1, :] , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.cat((all_true, keep_mask) , dim=1 ) __SCREAMING_SNAKE_CASE = keep_mask[:, :-1, :] __SCREAMING_SNAKE_CASE = keep_mask.gather(1 , indices.argsort(1 ) ) __SCREAMING_SNAKE_CASE = log_p_x_0.clone() __SCREAMING_SNAKE_CASE = -torch.inf # -inf = log(0) return rv
54
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Any = logging.get_logger(__name__) a_ : List[Any] = { """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/config.json""", """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/config.json""" # See all FNet models at https://huggingface.co/models?filter=fnet } class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "fnet" def __init__( self , UpperCamelCase=3_2000 , UpperCamelCase=768 , UpperCamelCase=12 , UpperCamelCase=3072 , UpperCamelCase="gelu_new" , UpperCamelCase=0.1 , UpperCamelCase=512 , UpperCamelCase=4 , UpperCamelCase=0.02 , UpperCamelCase=1e-12 , UpperCamelCase=False , UpperCamelCase=512 , UpperCamelCase=3 , UpperCamelCase=1 , UpperCamelCase=2 , **UpperCamelCase , ): """simple docstring""" super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) lowerCamelCase_ = vocab_size lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = initializer_range lowerCamelCase_ = type_vocab_size lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = use_tpu_fourier_optimizations lowerCamelCase_ = tpu_short_seq_length
55
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : list[int] ) -> None: A = len(A_ ) A = [0] * len_array if len_array > 0: A = array[0] for i in range(1 ,A_ ): A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ) -> bool: A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(A_ ) return False if __name__ == "__main__": import doctest doctest.testmod()
74
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class a ( unittest.TestCase ): def A_ ( self : Tuple ): snake_case_ = tempfile.mkdtemp() # fmt: off snake_case_ = ['''''', '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on snake_case_ = dict(zip(lowercase_ , range(len(lowercase_ ) ) ) ) snake_case_ = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] snake_case_ = {'''unk_token''': '''<unk>'''} snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowercase_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowercase_ ) ) snake_case_ = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.4814_5466, 0.457_8275, 0.4082_1073], '''image_std''': [0.2686_2954, 0.2613_0258, 0.2757_7711], } snake_case_ = os.path.join(self.tmpdirname , lowercase_ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(lowercase_ , lowercase_ ) def A_ ( self : Tuple , **lowercase_ : Tuple ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='''!''' , **lowercase_ ) def A_ ( self : int , **lowercase_ : int ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='''!''' , **lowercase_ ) def A_ ( self : Dict , **lowercase_ : Optional[Any] ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **lowercase_ ) def A_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def A_ ( self : Tuple ): snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(lowercase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : Dict ): snake_case_ = self.get_tokenizer() snake_case_ = self.get_rust_tokenizer() snake_case_ = self.get_image_processor() snake_case_ = OwlViTProcessor(tokenizer=lowercase_ , image_processor=lowercase_ ) processor_slow.save_pretrained(self.tmpdirname ) snake_case_ = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase_ ) snake_case_ = OwlViTProcessor(tokenizer=lowercase_ , image_processor=lowercase_ ) processor_fast.save_pretrained(self.tmpdirname ) snake_case_ = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowercase_ ) self.assertIsInstance(processor_fast.tokenizer , lowercase_ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowercase_ ) self.assertIsInstance(processor_fast.image_processor , lowercase_ ) def A_ ( self : Optional[Any] ): snake_case_ = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) snake_case_ = self.get_image_processor(do_normalize=lowercase_ ) snake_case_ = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=lowercase_ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowercase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowercase_ ) def A_ ( self : str ): snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = OwlViTProcessor(tokenizer=lowercase_ , image_processor=lowercase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(lowercase_ , return_tensors='''np''' ) snake_case_ = processor(images=lowercase_ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Union[str, Any] ): snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = OwlViTProcessor(tokenizer=lowercase_ , image_processor=lowercase_ ) snake_case_ = '''lower newer''' snake_case_ = processor(text=lowercase_ , return_tensors='''np''' ) snake_case_ = tokenizer(lowercase_ , return_tensors='''np''' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def A_ ( self : Any ): snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = OwlViTProcessor(tokenizer=lowercase_ , image_processor=lowercase_ ) snake_case_ = '''lower newer''' snake_case_ = self.prepare_image_inputs() snake_case_ = processor(text=lowercase_ , images=lowercase_ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(lowercase_ ): processor() def A_ ( self : int ): snake_case_ = '''google/owlvit-base-patch32''' snake_case_ = OwlViTProcessor.from_pretrained(lowercase_ ) snake_case_ = ['''cat''', '''nasa badge'''] snake_case_ = processor(text=lowercase_ ) snake_case_ = 16 self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(lowercase_ ): processor() def A_ ( self : str ): snake_case_ = '''google/owlvit-base-patch32''' snake_case_ = OwlViTProcessor.from_pretrained(lowercase_ ) snake_case_ = [['''cat''', '''nasa badge'''], ['''person''']] snake_case_ = processor(text=lowercase_ ) snake_case_ = 16 snake_case_ = len(lowercase_ ) snake_case_ = max([len(lowercase_ ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(lowercase_ ): processor() def A_ ( self : Union[str, Any] ): snake_case_ = '''google/owlvit-base-patch32''' snake_case_ = OwlViTProcessor.from_pretrained(lowercase_ ) snake_case_ = ['''cat''', '''nasa badge'''] snake_case_ = processor(text=lowercase_ ) snake_case_ = 16 snake_case_ = inputs['''input_ids'''] snake_case_ = [ [4_9406, 2368, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_9406, 6841, 1_1301, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask'''] ) self.assertEqual(inputs['''input_ids'''].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def A_ ( self : List[str] ): snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = OwlViTProcessor(tokenizer=lowercase_ , image_processor=lowercase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = self.prepare_image_inputs() snake_case_ = processor(images=lowercase_ , query_images=lowercase_ ) self.assertListEqual(list(inputs.keys() ) , ['''query_pixel_values''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(lowercase_ ): processor() def A_ ( self : Any ): snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = OwlViTProcessor(tokenizer=lowercase_ , image_processor=lowercase_ ) snake_case_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case_ = processor.batch_decode(lowercase_ ) snake_case_ = tokenizer.batch_decode(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ )
56
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = RobertaPreLayerNormConfig.from_pretrained( snake_case__ , architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict A = torch.load(hf_hub_download(repo_id=snake_case__ , filename='pytorch_model.bin' ) ) A = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): A = 'roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue A = tensor_value A = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=snake_case__ , config=snake_case__ , state_dict=snake_case__ ) model.save_pretrained(snake_case__ ) # convert tokenizer A = AutoTokenizer.from_pretrained(snake_case__ ) tokenizer.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
74
0
"""simple docstring""" import inspect import unittest from transformers import DPTConfig from transformers.file_utils import 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class _UpperCamelCase : '''simple docstring''' def __init__( self , __a , __a=2 , __a=32 , __a=16 , __a=3 , __a=True , __a=True , __a=32 , __a=4 , __a=[0, 1, 2, 3] , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=0.0_2 , __a=3 , __a=[1, 3_84, 24, 24] , __a=True , __a=None , ): __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = backbone_out_indices __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = initializer_range __lowerCAmelCase = num_labels __lowerCAmelCase = backbone_featmap_shape __lowerCAmelCase = scope __lowerCAmelCase = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 1 def snake_case ( self ): __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def snake_case ( self ): __lowerCAmelCase = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, "hidden_sizes": [96, 1_92, 3_84, 7_68], "num_groups": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__a , backbone_featmap_shape=self.backbone_featmap_shape , ) def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = DPTModel(config=__a ) model.to(__a ) model.eval() __lowerCAmelCase = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = self.num_labels __lowerCAmelCase = DPTForDepthEstimation(__a ) model.to(__a ) model.eval() __lowerCAmelCase = model(__a ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = self.num_labels __lowerCAmelCase = DPTForSemanticSegmentation(__a ) model.to(__a ) model.eval() __lowerCAmelCase = model(__a , labels=__a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def snake_case ( self ): __lowerCAmelCase = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _UpperCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () __UpperCAmelCase : List[Any] =( { """depth-estimation""": DPTForDepthEstimation, """feature-extraction""": DPTModel, """image-segmentation""": DPTForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : Any =False __UpperCAmelCase : Optional[int] =False __UpperCAmelCase : str =False def snake_case ( self ): __lowerCAmelCase = DPTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def snake_case ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="DPT does not use inputs_embeds" ) def snake_case ( self ): pass def snake_case ( self ): __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def snake_case ( self ): __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(__a ) __lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) def snake_case ( self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def snake_case ( self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*__a ) def snake_case ( self ): __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__a ) def snake_case ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True if model_class in get_values(__a ): continue __lowerCAmelCase = model_class(__a ) model.to(__a ) model.train() __lowerCAmelCase = self._prepare_for_class(__a , __a , return_labels=__a ) __lowerCAmelCase = model(**__a ).loss loss.backward() def snake_case ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = False __lowerCAmelCase = True if model_class in get_values(__a ) or not model_class.supports_gradient_checkpointing: continue __lowerCAmelCase = model_class(__a ) model.to(__a ) model.gradient_checkpointing_enable() model.train() __lowerCAmelCase = self._prepare_for_class(__a , __a , return_labels=__a ) __lowerCAmelCase = model(**__a ).loss loss.backward() def snake_case ( self ): __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = _config_zero_init(__a ) for model_class in self.all_model_classes: __lowerCAmelCase = model_class(config=__a ) # Skip the check for the backbone __lowerCAmelCase = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": __lowerCAmelCase = [f"{name}.{key}" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def snake_case ( self ): pass @slow def snake_case ( self ): for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: __lowerCAmelCase = DPTModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def snake_case ( self ): # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = "add" with self.assertRaises(__a ): __lowerCAmelCase = DPTForDepthEstimation(__a ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision @slow class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): __lowerCAmelCase = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas" ) __lowerCAmelCase = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas" ).to(__a ) __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=__a , return_tensors="pt" ).to(__a ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**__a ) __lowerCAmelCase = outputs.predicted_depth # verify the predicted depth __lowerCAmelCase = torch.Size((1, 3_84, 3_84) ) self.assertEqual(predicted_depth.shape , __a ) __lowerCAmelCase = torch.tensor( [[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]] ).to(__a ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_00 , __a , atol=1e-4 ) )
57
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''roformer''' def __init__( self : Tuple ,A_ : Optional[int]=5_0000 ,A_ : Tuple=None ,A_ : Optional[Any]=768 ,A_ : Dict=12 ,A_ : Optional[int]=12 ,A_ : Union[str, Any]=3072 ,A_ : Dict="gelu" ,A_ : Dict=0.1 ,A_ : List[Any]=0.1 ,A_ : List[Any]=1536 ,A_ : List[str]=2 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : Optional[int]=0 ,A_ : List[str]=False ,A_ : Tuple=True ,**A_ : List[str] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size if embedding_size is None else embedding_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = rotary_value A = use_cache class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
74
0
'''simple docstring''' import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any]=False ) ->Optional[int]: _SCREAMING_SNAKE_CASE = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith("""head""" ): _SCREAMING_SNAKE_CASE = """segformer.encoder.""" + key if key.startswith("""backbone""" ): _SCREAMING_SNAKE_CASE = key.replace("""backbone""" , """segformer.encoder""" ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 _SCREAMING_SNAKE_CASE = key[key.find("""patch_embed""" ) + len("""patch_embed""" )] _SCREAMING_SNAKE_CASE = key.replace(F'patch_embed{idx}' , F'patch_embeddings.{int(__lowerCamelCase )-1}' ) if "norm" in key: _SCREAMING_SNAKE_CASE = key.replace("""norm""" , """layer_norm""" ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 _SCREAMING_SNAKE_CASE = key[key.find("""segformer.encoder.layer_norm""" ) + len("""segformer.encoder.layer_norm""" )] _SCREAMING_SNAKE_CASE = key.replace(F'layer_norm{idx}' , F'layer_norm.{int(__lowerCamelCase )-1}' ) if "layer_norm1" in key: _SCREAMING_SNAKE_CASE = key.replace("""layer_norm1""" , """layer_norm_1""" ) if "layer_norm2" in key: _SCREAMING_SNAKE_CASE = key.replace("""layer_norm2""" , """layer_norm_2""" ) if "block" in key: # replace for example block1 by block.0 _SCREAMING_SNAKE_CASE = key[key.find("""block""" ) + len("""block""" )] _SCREAMING_SNAKE_CASE = key.replace(F'block{idx}' , F'block.{int(__lowerCamelCase )-1}' ) if "attn.q" in key: _SCREAMING_SNAKE_CASE = key.replace("""attn.q""" , """attention.self.query""" ) if "attn.proj" in key: _SCREAMING_SNAKE_CASE = key.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in key: _SCREAMING_SNAKE_CASE = key.replace("""attn""" , """attention.self""" ) if "fc1" in key: _SCREAMING_SNAKE_CASE = key.replace("""fc1""" , """dense1""" ) if "fc2" in key: _SCREAMING_SNAKE_CASE = key.replace("""fc2""" , """dense2""" ) if "linear_pred" in key: _SCREAMING_SNAKE_CASE = key.replace("""linear_pred""" , """classifier""" ) if "linear_fuse" in key: _SCREAMING_SNAKE_CASE = key.replace("""linear_fuse.conv""" , """linear_fuse""" ) _SCREAMING_SNAKE_CASE = key.replace("""linear_fuse.bn""" , """batch_norm""" ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 _SCREAMING_SNAKE_CASE = key[key.find("""linear_c""" ) + len("""linear_c""" )] _SCREAMING_SNAKE_CASE = key.replace(F'linear_c{idx}' , F'linear_c.{int(__lowerCamelCase )-1}' ) if key.startswith("""head""" ): _SCREAMING_SNAKE_CASE = key.replace("""head""" , """classifier""" ) _SCREAMING_SNAKE_CASE = value return new_state_dict def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Any ) ->str: # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) _SCREAMING_SNAKE_CASE = state_dict.pop(F'segformer.encoder.block.{i}.{j}.attention.self.kv.weight' ) _SCREAMING_SNAKE_CASE = state_dict.pop(F'segformer.encoder.block.{i}.{j}.attention.self.kv.bias' ) # next, add keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE = kv_weight[ : config.hidden_sizes[i], : ] _SCREAMING_SNAKE_CASE = kv_bias[: config.hidden_sizes[i]] _SCREAMING_SNAKE_CASE = kv_weight[ config.hidden_sizes[i] :, : ] _SCREAMING_SNAKE_CASE = kv_bias[ config.hidden_sizes[i] : ] def lowerCamelCase ( ) ->List[str]: _SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" _SCREAMING_SNAKE_CASE = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ) return image @torch.no_grad() def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple ) ->Tuple: _SCREAMING_SNAKE_CASE = SegformerConfig() _SCREAMING_SNAKE_CASE = False # set attributes based on model_name _SCREAMING_SNAKE_CASE = """huggingface/label-files""" if "segformer" in model_name: _SCREAMING_SNAKE_CASE = model_name[len("""segformer.""" ) : len("""segformer.""" ) + 2] if "ade" in model_name: _SCREAMING_SNAKE_CASE = 150 _SCREAMING_SNAKE_CASE = """ade20k-id2label.json""" _SCREAMING_SNAKE_CASE = (1, 150, 128, 128) elif "city" in model_name: _SCREAMING_SNAKE_CASE = 19 _SCREAMING_SNAKE_CASE = """cityscapes-id2label.json""" _SCREAMING_SNAKE_CASE = (1, 19, 128, 128) else: raise ValueError(F'Model {model_name} not supported' ) elif "mit" in model_name: _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = model_name[4:6] _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = (1, 1000) else: raise ValueError(F'Model {model_name} not supported' ) # set config attributes _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE = idalabel _SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": _SCREAMING_SNAKE_CASE = [64, 128, 320, 512] _SCREAMING_SNAKE_CASE = 256 elif size == "b2": _SCREAMING_SNAKE_CASE = [64, 128, 320, 512] _SCREAMING_SNAKE_CASE = 768 _SCREAMING_SNAKE_CASE = [3, 4, 6, 3] elif size == "b3": _SCREAMING_SNAKE_CASE = [64, 128, 320, 512] _SCREAMING_SNAKE_CASE = 768 _SCREAMING_SNAKE_CASE = [3, 4, 18, 3] elif size == "b4": _SCREAMING_SNAKE_CASE = [64, 128, 320, 512] _SCREAMING_SNAKE_CASE = 768 _SCREAMING_SNAKE_CASE = [3, 8, 27, 3] elif size == "b5": _SCREAMING_SNAKE_CASE = [64, 128, 320, 512] _SCREAMING_SNAKE_CASE = 768 _SCREAMING_SNAKE_CASE = [3, 6, 40, 3] else: raise ValueError(F'Size {size} not supported' ) # load image processor (only resize + normalize) _SCREAMING_SNAKE_CASE = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__lowerCamelCase , align=__lowerCamelCase , do_random_crop=__lowerCamelCase ) # prepare image _SCREAMING_SNAKE_CASE = prepare_img() _SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="""pt""" ).pixel_values logger.info(F'Converting model {model_name}...' ) # load original state dict if encoder_only: _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , map_location=torch.device("""cpu""" ) ) else: _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , map_location=torch.device("""cpu""" ) )["""state_dict"""] # rename keys _SCREAMING_SNAKE_CASE = rename_keys(__lowerCamelCase , encoder_only=__lowerCamelCase ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(__lowerCamelCase , __lowerCamelCase ) # create HuggingFace model and load state dict if encoder_only: _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = SegformerForImageClassification(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = SegformerForSemanticSegmentation(__lowerCamelCase ) model.load_state_dict(__lowerCamelCase ) model.eval() # forward pass _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-7.5820, -8.7231, -8.3215], [-8.0600, -10.3529, -10.0304], [-7.5208, -9.4103, -9.6239]], [[-12.6918, -13.8994, -13.7137], [-13.3196, -15.7523, -15.4789], [-12.9343, -14.8757, -14.9689]], [[-11.1911, -11.9421, -11.3243], [-11.3342, -13.6839, -13.3581], [-10.3909, -12.1832, -12.4858]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-11.8173, -14.3850, -16.3128], [-14.5648, -16.5804, -18.6568], [-14.7223, -15.7387, -18.4218]], [[-15.7290, -17.9171, -19.4423], [-18.3105, -19.9448, -21.4661], [-17.9296, -18.6497, -20.7910]], [[-15.0783, -17.0336, -18.2789], [-16.8771, -18.6870, -20.1612], [-16.2454, -17.1426, -19.5055]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-9.0878, -10.2081, -10.1891], [-9.3144, -10.7941, -10.9843], [-9.2294, -10.3855, -10.5704]], [[-12.2316, -13.9068, -13.6102], [-12.9161, -14.3702, -14.3235], [-12.5233, -13.7174, -13.7932]], [[-14.6275, -15.2490, -14.9727], [-14.3400, -15.9687, -16.2827], [-14.1484, -15.4033, -15.8937]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-12.3144, -13.2447, -14.0802], [-13.3614, -14.5816, -15.6117], [-13.3340, -14.4433, -16.2219]], [[-19.2781, -20.4128, -20.7506], [-20.6153, -21.6566, -22.0998], [-19.9800, -21.0430, -22.1494]], [[-18.8739, -19.7804, -21.1834], [-20.1233, -21.6765, -23.2944], [-20.0315, -21.2641, -23.6944]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-9.5524, -12.0835, -11.7348], [-10.5229, -13.6446, -14.5662], [-9.5842, -12.8851, -13.9414]], [[-15.3432, -17.5323, -17.0818], [-16.3330, -18.9255, -19.2101], [-15.1340, -17.7848, -18.3971]], [[-12.6072, -14.9486, -14.6631], [-13.7629, -17.0907, -17.7745], [-12.7899, -16.1695, -17.1671]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-11.9295, -13.4057, -14.8106], [-13.3431, -14.8179, -15.3781], [-14.2836, -15.5942, -16.1588]], [[-11.4906, -12.8067, -13.6564], [-13.1189, -14.0500, -14.1543], [-13.8748, -14.5136, -14.8789]], [[0.5374, 0.1067, -0.4742], [0.1141, -0.2255, -0.7099], [-0.3000, -0.5924, -1.3105]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-7.8217, -9.8767, -10.1717], [-9.4438, -10.9058, -11.4047], [-9.7939, -12.3495, -12.1079]], [[-7.1514, -9.5336, -10.0860], [-9.7776, -11.6822, -11.8439], [-10.1411, -12.7655, -12.8972]], [[0.3021, 0.0805, -0.2310], [-0.0328, -0.1605, -0.2714], [-0.1408, -0.5477, -0.6976]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [ [-1.1_3_7_2e0_1, -1.2_7_8_7e0_1, -1.3_4_7_7e0_1], [-1.2_5_3_6e0_1, -1.4_1_9_4e0_1, -1.4_4_0_9e0_1], [-1.3_2_1_7e0_1, -1.4_8_8_8e0_1, -1.5_3_2_7e0_1], ], [ [-1.4_7_9_1e0_1, -1.7_1_2_2e0_1, -1.8_2_7_7e0_1], [-1.7_1_6_3e0_1, -1.9_1_9_2e0_1, -1.9_5_3_3e0_1], [-1.7_8_9_7e0_1, -1.9_9_9_1e0_1, -2.0_3_1_5e0_1], ], [ [7.6_7_2_3e-0_1, 4.1_9_2_1e-0_1, -7.7_8_7_8e-0_2], [4.7_7_7_2e-0_1, 9.5_5_5_7e-0_3, -2.8_0_8_2e-0_1], [3.6_0_3_2e-0_1, -2.4_8_2_6e-0_1, -5.1_1_6_8e-0_1], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-9.4959, -11.3087, -11.7479], [-11.0025, -12.6540, -12.3319], [-11.4064, -13.0487, -12.9905]], [[-9.8905, -11.3084, -12.0854], [-11.1726, -12.7698, -12.9583], [-11.5985, -13.3278, -14.1774]], [[0.2213, 0.0192, -0.2466], [-0.1731, -0.4213, -0.4874], [-0.3126, -0.6541, -1.1389]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-16.0976, -16.4856, -17.3962], [-16.6234, -19.0342, -19.7685], [-16.0900, -18.0661, -19.1180]], [[-18.4750, -18.8488, -19.5074], [-19.4030, -22.1570, -22.5977], [-19.1191, -20.8486, -22.3783]], [[-4.5178, -5.5037, -6.5109], [-5.0884, -7.2174, -8.0334], [-4.4156, -5.8117, -7.2970]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-14.2081, -14.4732, -14.1977], [-14.5867, -16.4423, -16.6356], [-13.4441, -14.9685, -16.8696]], [[-14.4576, -14.7073, -15.0451], [-15.0816, -17.6237, -17.9873], [-14.4213, -16.0199, -18.5992]], [[-4.7349, -4.9588, -5.0966], [-4.3210, -6.9325, -7.2591], [-3.4312, -4.7484, -7.1917]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-11.7737, -11.9526, -11.3273], [-13.6692, -14.4574, -13.8878], [-13.8937, -14.6924, -15.9345]], [[-14.6706, -14.5330, -14.1306], [-16.1502, -16.8180, -16.4269], [-16.8338, -17.8939, -20.1746]], [[1.0491, 0.8289, 1.0310], [1.1044, 0.5219, 0.8055], [1.0899, 0.6926, 0.5590]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": _SCREAMING_SNAKE_CASE = torch.tensor( [ [[-12.5641, -13.4777, -13.0684], [-13.9587, -15.8983, -16.6557], [-13.3109, -15.7350, -16.3141]], [[-14.7074, -15.4352, -14.5944], [-16.6353, -18.1663, -18.6120], [-15.1702, -18.0329, -18.1547]], [[-1.7990, -2.0951, -1.7784], [-2.6397, -3.8245, -3.9686], [-1.5264, -2.8126, -2.9316]], ] ) else: _SCREAMING_SNAKE_CASE = logits.argmax(-1 ).item() print("""Predicted class:""" , model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , __lowerCamelCase , atol=1e-2 ) # finally, save model and image processor logger.info(F'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' ) Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase ) model.save_pretrained(__lowerCamelCase ) image_processor.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( """--model_name""", default="""segformer.b0.512x512.ade.160k""", type=str, help="""Name of the model you'd like to convert.""", ) parser.add_argument( """--checkpoint_path""", default=None, type=str, help="""Path to the original PyTorch checkpoint (.pth file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) lowercase_ = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
58
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : Dict ): A = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : int ): A , A = emb.weight.shape A = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A = emb.weight.data return lin_layer def _snake_case ( snake_case__ : List[str] , snake_case__ : Any="facebook/mbart-large-en-ro" , snake_case__ : Optional[int]=False , snake_case__ : List[str]=False ): A = torch.load(snake_case__ , map_location='cpu' )['model'] remove_ignore_keys_(snake_case__ ) A = state_dict['encoder.embed_tokens.weight'].shape[0] A = MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: A = 'relu' A = state_dict['decoder.embed_tokens.weight'] A = MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: A = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowercase = 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''') _lowercase = parser.parse_args() _lowercase = 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)
74
0
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __lowerCamelCase = logging.get_logger(__name__) def UpperCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : List[Any] ): snake_case : int = set() snake_case : Tuple = [] def parse_line(__lowerCamelCase : Optional[Any] ): for line in fp: if isinstance(__lowerCamelCase , __lowerCamelCase ): snake_case : Tuple = line.decode("UTF-8" ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(" " ): # process a single warning and move it to `selected_warnings`. if len(__lowerCamelCase ) > 0: snake_case : List[str] = "\n".join(__lowerCamelCase ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(__lowerCamelCase ) buffer.clear() continue else: snake_case : Tuple = line.strip() buffer.append(__lowerCamelCase ) if from_gh: for filename in os.listdir(__lowerCamelCase ): snake_case : List[Any] = os.path.join(__lowerCamelCase , __lowerCamelCase ) if not os.path.isdir(__lowerCamelCase ): # read the file if filename != "warnings.txt": continue with open(__lowerCamelCase ) as fp: parse_line(__lowerCamelCase ) else: try: with zipfile.ZipFile(__lowerCamelCase ) as z: for filename in z.namelist(): if not os.path.isdir(__lowerCamelCase ): # read the file if filename != "warnings.txt": continue with z.open(__lowerCamelCase ) as fp: parse_line(__lowerCamelCase ) except Exception: logger.warning( f"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : str ): snake_case : Union[str, Any] = set() snake_case : List[Any] = [os.path.join(__lowerCamelCase , __lowerCamelCase ) for p in os.listdir(__lowerCamelCase ) if (p.endswith(".zip" ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(__lowerCamelCase , __lowerCamelCase ) ) return selected_warnings if __name__ == "__main__": def UpperCamelCase ( __lowerCamelCase : Union[str, Any] ): return values.split("," ) __lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) __lowerCamelCase = parser.parse_args() __lowerCamelCase = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links __lowerCamelCase = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts __lowerCamelCase = extract_warnings(args.output_dir, args.targets) __lowerCamelCase = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
59
"""simple docstring""" import argparse import struct import unittest class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : bytes ) -> None: A = data # Initialize hash values A = [ 0X6_A_0_9_E_6_6_7, 0XB_B_6_7_A_E_8_5, 0X3_C_6_E_F_3_7_2, 0XA_5_4_F_F_5_3_A, 0X5_1_0_E_5_2_7_F, 0X9_B_0_5_6_8_8_C, 0X1_F_8_3_D_9_A_B, 0X5_B_E_0_C_D_1_9, ] # Initialize round constants A = [ 0X4_2_8_A_2_F_9_8, 0X7_1_3_7_4_4_9_1, 0XB_5_C_0_F_B_C_F, 0XE_9_B_5_D_B_A_5, 0X3_9_5_6_C_2_5_B, 0X5_9_F_1_1_1_F_1, 0X9_2_3_F_8_2_A_4, 0XA_B_1_C_5_E_D_5, 0XD_8_0_7_A_A_9_8, 0X1_2_8_3_5_B_0_1, 0X2_4_3_1_8_5_B_E, 0X5_5_0_C_7_D_C_3, 0X7_2_B_E_5_D_7_4, 0X8_0_D_E_B_1_F_E, 0X9_B_D_C_0_6_A_7, 0XC_1_9_B_F_1_7_4, 0XE_4_9_B_6_9_C_1, 0XE_F_B_E_4_7_8_6, 0X0_F_C_1_9_D_C_6, 0X2_4_0_C_A_1_C_C, 0X2_D_E_9_2_C_6_F, 0X4_A_7_4_8_4_A_A, 0X5_C_B_0_A_9_D_C, 0X7_6_F_9_8_8_D_A, 0X9_8_3_E_5_1_5_2, 0XA_8_3_1_C_6_6_D, 0XB_0_0_3_2_7_C_8, 0XB_F_5_9_7_F_C_7, 0XC_6_E_0_0_B_F_3, 0XD_5_A_7_9_1_4_7, 0X0_6_C_A_6_3_5_1, 0X1_4_2_9_2_9_6_7, 0X2_7_B_7_0_A_8_5, 0X2_E_1_B_2_1_3_8, 0X4_D_2_C_6_D_F_C, 0X5_3_3_8_0_D_1_3, 0X6_5_0_A_7_3_5_4, 0X7_6_6_A_0_A_B_B, 0X8_1_C_2_C_9_2_E, 0X9_2_7_2_2_C_8_5, 0XA_2_B_F_E_8_A_1, 0XA_8_1_A_6_6_4_B, 0XC_2_4_B_8_B_7_0, 0XC_7_6_C_5_1_A_3, 0XD_1_9_2_E_8_1_9, 0XD_6_9_9_0_6_2_4, 0XF_4_0_E_3_5_8_5, 0X1_0_6_A_A_0_7_0, 0X1_9_A_4_C_1_1_6, 0X1_E_3_7_6_C_0_8, 0X2_7_4_8_7_7_4_C, 0X3_4_B_0_B_C_B_5, 0X3_9_1_C_0_C_B_3, 0X4_E_D_8_A_A_4_A, 0X5_B_9_C_C_A_4_F, 0X6_8_2_E_6_F_F_3, 0X7_4_8_F_8_2_E_E, 0X7_8_A_5_6_3_6_F, 0X8_4_C_8_7_8_1_4, 0X8_C_C_7_0_2_0_8, 0X9_0_B_E_F_F_F_A, 0XA_4_5_0_6_C_E_B, 0XB_E_F_9_A_3_F_7, 0XC_6_7_1_7_8_F_2, ] A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : bytes ) -> bytes: A = B'\x80' + (B'\x00' * (63 - (len(A_ ) + 8) % 64)) A = struct.pack('>Q' ,(len(A_ ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: # Convert into blocks of 64 bytes A = [ self.preprocessed_data[x : x + 64] for x in range(0 ,len(self.preprocessed_data ) ,64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers A = list(struct.unpack('>16L' ,A_ ) ) # add 48 0-ed integers words += [0] * 48 A , A , A , A , A , A , A , A = self.hashes for index in range(0 ,64 ): if index > 15: # modify the zero-ed indexes at the end of the array A = ( self.ror(words[index - 15] ,7 ) ^ self.ror(words[index - 15] ,18 ) ^ (words[index - 15] >> 3) ) A = ( self.ror(words[index - 2] ,17 ) ^ self.ror(words[index - 2] ,19 ) ^ (words[index - 2] >> 10) ) A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0_0_0_0_0_0_0_0 # Compression A = self.ror(A_ ,6 ) ^ self.ror(A_ ,11 ) ^ self.ror(A_ ,25 ) A = (e & f) ^ ((~e & 0XF_F_F_F_F_F_F_F) & g) A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0_0_0_0_0_0_0_0 A = self.ror(A_ ,2 ) ^ self.ror(A_ ,13 ) ^ self.ror(A_ ,22 ) A = (a & b) ^ (a & c) ^ (b & c) A = (sa + maj) % 0X1_0_0_0_0_0_0_0_0 A , A , A , A , A , A , A , A = ( g, f, e, ((d + tempa) % 0X1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0X1_0_0_0_0_0_0_0_0), ) A = [a, b, c, d, e, f, g, h] # Modify final values A = [ ((element + mutated_hash_values[index]) % 0X1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] A = ''.join([hex(A_ )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : int ) -> int: return 0XF_F_F_F_F_F_F_F & (value << (32 - rotations)) | (value >> rotations) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> None: import hashlib A = bytes('Test String' ,'utf-8' ) self.assertEqual(SHAaaa(A_ ).hash ,hashlib.shaaaa(A_ ).hexdigest() ) def _snake_case ( ): import doctest doctest.testmod() A = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) A = parser.parse_args() A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: A = f.read() else: A = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
74
0
"""simple docstring""" import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def _snake_case ( _snake_case : Tuple ): if isinstance(_snake_case , collections.abc.Iterable ): return x return (x, x) @require_flax class snake_case_: def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Dict ): pass def lowerCamelCase__ ( self : Any ): pass def lowerCamelCase__ ( self : int ): pass def lowerCamelCase__ ( self : Tuple , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : float ): lowerCAmelCase : List[str] = np.abs((a - b) ).max() self.assertLessEqual(UpperCamelCase_ , UpperCamelCase_ , F'''Difference between torch and flax is {diff} (>= {tol}).''' ) def lowerCamelCase__ ( self : int , UpperCamelCase_ : List[str] , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : str , UpperCamelCase_ : Tuple=None , **UpperCamelCase_ : Dict ): lowerCAmelCase : str = VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : List[Any] = FlaxVisionTextDualEncoderModel(UpperCamelCase_ ) lowerCAmelCase : int = model(input_ids=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], config.projection_dim) ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[str]=None , **UpperCamelCase_ : List[Any] ): lowerCAmelCase, lowerCAmelCase : Optional[Any] = self.get_vision_text_model(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : int = {'''vision_model''': vision_model, '''text_model''': text_model} lowerCAmelCase : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = model(input_ids=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], model.config.projection_dim) ) def lowerCamelCase__ ( self : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : int=None , **UpperCamelCase_ : Tuple ): lowerCAmelCase, lowerCAmelCase : Optional[Any] = self.get_vision_text_model(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : int = {'''vision_model''': vision_model, '''text_model''': text_model} lowerCAmelCase : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = model(input_ids=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ ) lowerCAmelCase : List[Any] = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase_ ) lowerCAmelCase : Tuple = model(input_ids=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ ) lowerCAmelCase : int = after_output[0] lowerCAmelCase : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase_ , 1E-3 ) def lowerCamelCase__ ( self : Tuple , UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple=None , **UpperCamelCase_ : Any ): lowerCAmelCase, lowerCAmelCase : Tuple = self.get_vision_text_model(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = {'''vision_model''': vision_model, '''text_model''': text_model} lowerCAmelCase : Optional[int] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase_ ) lowerCAmelCase : str = model( input_ids=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ , output_attentions=UpperCamelCase_ ) lowerCAmelCase : int = output.vision_model_output.attentions self.assertEqual(len(UpperCamelCase_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase : str = to_atuple(vision_model.config.image_size ) lowerCAmelCase : Optional[int] = to_atuple(vision_model.config.patch_size ) lowerCAmelCase : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowerCAmelCase : Optional[int] = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowerCAmelCase : Any = output.text_model_output.attentions self.assertEqual(len(UpperCamelCase_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : List[str] , UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] ): pt_model.to(UpperCamelCase_ ) pt_model.eval() # prepare inputs lowerCAmelCase : Dict = inputs_dict lowerCAmelCase : List[Any] = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): lowerCAmelCase : Optional[int] = pt_model(**UpperCamelCase_ ).to_tuple() lowerCAmelCase : Optional[int] = fx_model(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(UpperCamelCase_ , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase_ , from_pt=UpperCamelCase_ ) lowerCAmelCase : Dict = fx_model_loaded(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(UpperCamelCase_ , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : Dict = VisionTextDualEncoderModel.from_pretrained(UpperCamelCase_ , from_flax=UpperCamelCase_ ) pt_model_loaded.to(UpperCamelCase_ ) pt_model_loaded.eval() with torch.no_grad(): lowerCAmelCase : str = pt_model_loaded(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(UpperCamelCase_ , pt_output_loaded.numpy() , 4E-2 ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[str] ): lowerCAmelCase : Any = VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = VisionTextDualEncoderModel(UpperCamelCase_ ) lowerCAmelCase : int = FlaxVisionTextDualEncoderModel(UpperCamelCase_ ) lowerCAmelCase : Dict = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = fx_state self.check_pt_flax_equivalence(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Union[str, Any] ): lowerCAmelCase : Any = VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = VisionTextDualEncoderModel(UpperCamelCase_ ) lowerCAmelCase : List[Any] = FlaxVisionTextDualEncoderModel(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = load_flax_weights_in_pytorch_model(UpperCamelCase_ , fx_model.params ) self.check_pt_flax_equivalence(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : Any = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Any = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**UpperCamelCase_ ) def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() self.check_save_load(**UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**UpperCamelCase_ ) @is_pt_flax_cross_test def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : List[str] = self.prepare_config_and_inputs() lowerCAmelCase : Any = config_inputs_dict.pop('''vision_config''' ) lowerCAmelCase : Optional[int] = config_inputs_dict.pop('''text_config''' ) lowerCAmelCase : Union[str, Any] = config_inputs_dict self.check_equivalence_pt_to_flax(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) self.check_equivalence_flax_to_pt(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) @slow def lowerCamelCase__ ( self : Any ): lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self.get_pretrained_model_and_inputs() lowerCAmelCase : List[Any] = model_a(**UpperCamelCase_ ) lowerCAmelCase : int = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : Any = FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase_ ) lowerCAmelCase : Tuple = model_a(**UpperCamelCase_ ) lowerCAmelCase : List[str] = after_outputs[0] lowerCAmelCase : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase_ , 1E-5 ) @require_flax class snake_case_( a__ , unittest.TestCase ): def lowerCamelCase__ ( self : int ): lowerCAmelCase : Tuple = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-vit''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=UpperCamelCase_ , text_from_pt=UpperCamelCase_ , ) lowerCAmelCase : Optional[Any] = 1_3 lowerCAmelCase : Any = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) lowerCAmelCase : List[str] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) lowerCAmelCase : Dict = random_attention_mask([batch_size, 4] ) lowerCAmelCase : str = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Union[str, Any] ): lowerCAmelCase : List[str] = FlaxViTModel(UpperCamelCase_ ) lowerCAmelCase : List[str] = FlaxBertModel(UpperCamelCase_ ) return vision_model, text_model def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : List[str] = FlaxViTModelTester(self ) lowerCAmelCase : Dict = FlaxBertModelTester(self ) lowerCAmelCase : Optional[Any] = vit_model_tester.prepare_config_and_inputs() lowerCAmelCase : Optional[Any] = bert_model_tester.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase : str = vision_config_and_inputs lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Tuple = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class snake_case_( a__ , unittest.TestCase ): def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Dict = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-clip''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=UpperCamelCase_ , text_from_pt=UpperCamelCase_ , ) lowerCAmelCase : Optional[Any] = 1_3 lowerCAmelCase : Union[str, Any] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) lowerCAmelCase : Union[str, Any] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) lowerCAmelCase : List[str] = random_attention_mask([batch_size, 4] ) lowerCAmelCase : Optional[Any] = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def lowerCamelCase__ ( self : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] ): lowerCAmelCase : str = FlaxCLIPVisionModel(UpperCamelCase_ ) lowerCAmelCase : int = FlaxBertModel(UpperCamelCase_ ) return vision_model, text_model def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Tuple = FlaxCLIPVisionModelTester(self ) lowerCAmelCase : Dict = FlaxBertModelTester(self ) lowerCAmelCase : List[Any] = clip_model_tester.prepare_config_and_inputs() lowerCAmelCase : Union[str, Any] = bert_model_tester.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase : Dict = vision_config_and_inputs lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : int = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class snake_case_( unittest.TestCase ): @slow def lowerCamelCase__ ( self : Any ): lowerCAmelCase : int = FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian''' , logit_scale_init_value=1.0 ) lowerCAmelCase : Optional[Any] = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' ) lowerCAmelCase : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) lowerCAmelCase : Dict = processor( text=['''una foto di un gatto''', '''una foto di un cane'''] , images=UpperCamelCase_ , padding=UpperCamelCase_ , return_tensors='''np''' ) lowerCAmelCase : List[str] = model(**UpperCamelCase_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) lowerCAmelCase : str = np.array([[1.2_284_727, 0.3_104_122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , UpperCamelCase_ , atol=1E-3 ) )
60
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''DeiTFeatureExtractor'''] _lowercase = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDeiTForImageClassification''', '''TFDeiTForImageClassificationWithTeacher''', '''TFDeiTForMaskedImageModeling''', '''TFDeiTModel''', '''TFDeiTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
0
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html _a = 'platform' import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, __lowerCamelCase=None, ): if attention_mask is None: UpperCAmelCase_ : Union[str, Any] = np.where(input_ids != config.pad_token_id, 1, 0 ) if decoder_attention_mask is None: UpperCAmelCase_ : Optional[int] = np.where(decoder_input_ids != config.pad_token_id, 1, 0 ) if head_mask is None: UpperCAmelCase_ : int = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase_ : Union[str, Any] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase_ : List[Any] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class A_ : '''simple docstring''' def __init__( self , lowercase_ , lowercase_=13 , lowercase_=7 , lowercase_=True , lowercase_=False , lowercase_=99 , lowercase_=16 , lowercase_=2 , lowercase_=4 , lowercase_=4 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=32 , lowercase_=2 , lowercase_=1 , lowercase_=0 , lowercase_=0.02 , ): """simple docstring""" UpperCAmelCase_ : List[str] = parent UpperCAmelCase_ : Tuple = batch_size UpperCAmelCase_ : str = seq_length UpperCAmelCase_ : Dict = is_training UpperCAmelCase_ : List[Any] = use_labels UpperCAmelCase_ : Optional[int] = vocab_size UpperCAmelCase_ : int = hidden_size UpperCAmelCase_ : Optional[Any] = num_hidden_layers UpperCAmelCase_ : Dict = num_attention_heads UpperCAmelCase_ : List[str] = intermediate_size UpperCAmelCase_ : Optional[int] = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : int = attention_probs_dropout_prob UpperCAmelCase_ : Optional[Any] = max_position_embeddings UpperCAmelCase_ : str = eos_token_id UpperCAmelCase_ : str = pad_token_id UpperCAmelCase_ : str = bos_token_id UpperCAmelCase_ : List[Any] = initializer_range def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) UpperCAmelCase_ : Any = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) UpperCAmelCase_ : str = shift_tokens_right(lowercase_ , 1 , 2 ) UpperCAmelCase_ : str = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowercase_ , ) UpperCAmelCase_ : Optional[int] = prepare_blenderbot_inputs_dict(lowercase_ , lowercase_ , lowercase_ ) return config, inputs_dict def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : List[str] = 20 UpperCAmelCase_ : int = model_class_name(lowercase_ ) UpperCAmelCase_ : Optional[int] = model.encode(inputs_dict["input_ids"] ) UpperCAmelCase_ , UpperCAmelCase_ : Any = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) UpperCAmelCase_ : Any = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) UpperCAmelCase_ : Tuple = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) UpperCAmelCase_ : Union[str, Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCAmelCase_ : int = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) UpperCAmelCase_ : int = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) UpperCAmelCase_ : Dict = model.decode( decoder_input_ids[:, -1:] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase_ , ) UpperCAmelCase_ : Optional[Any] = model.decode(lowercase_ , lowercase_ ) UpperCAmelCase_ : Tuple = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : List[str] = 20 UpperCAmelCase_ : Any = model_class_name(lowercase_ ) UpperCAmelCase_ : Tuple = model.encode(inputs_dict["input_ids"] ) UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) UpperCAmelCase_ : Optional[Any] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) UpperCAmelCase_ : int = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) UpperCAmelCase_ : List[str] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCAmelCase_ : List[str] = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) UpperCAmelCase_ : Any = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) UpperCAmelCase_ : Dict = model.decode( decoder_input_ids[:, -1:] , lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase_ , decoder_position_ids=lowercase_ , ) UpperCAmelCase_ : Dict = model.decode(lowercase_ , lowercase_ , decoder_attention_mask=lowercase_ ) UpperCAmelCase_ : Optional[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) @require_flax class A_ (unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = 99 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) UpperCAmelCase_ : Any = input_ids.shape[0] UpperCAmelCase_ : Dict = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Tuple = self._get_config_and_data() UpperCAmelCase_ : List[str] = FlaxBlenderbotSmallForConditionalGeneration(lowercase_ ) UpperCAmelCase_ : Optional[int] = lm_model(input_ids=lowercase_ ) UpperCAmelCase_ : Optional[int] = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["logits"].shape , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[str] = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) UpperCAmelCase_ : Optional[int] = FlaxBlenderbotSmallForConditionalGeneration(lowercase_ ) UpperCAmelCase_ : str = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) UpperCAmelCase_ : str = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) UpperCAmelCase_ : Tuple = lm_model(input_ids=lowercase_ , decoder_input_ids=lowercase_ ) UpperCAmelCase_ : Tuple = (*summary.shape, config.vocab_size) self.assertEqual(outputs["logits"].shape , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[Any] = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) UpperCAmelCase_ : Dict = shift_tokens_right(lowercase_ , 1 , 2 ) UpperCAmelCase_ : Tuple = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() UpperCAmelCase_ : Optional[Any] = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowercase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class A_ (lowercase__ ,unittest.TestCase ,lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) SCREAMING_SNAKE_CASE__ : List[Any] = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Dict = FlaxBlenderbotSmallModelTester(self ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase_ , lowercase_ , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase_ , lowercase_ , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCAmelCase_ : List[Any] = self._prepare_for_class(lowercase_ , lowercase_ ) UpperCAmelCase_ : Dict = model_class(lowercase_ ) @jax.jit def encode_jitted(lowercase_ , lowercase_=None , **lowercase_ ): return model.encode(input_ids=lowercase_ , attention_mask=lowercase_ ) with self.subTest("JIT Enabled" ): UpperCAmelCase_ : List[Any] = encode_jitted(**lowercase_ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): UpperCAmelCase_ : Optional[Any] = encode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCAmelCase_ : Optional[int] = model_class(lowercase_ ) UpperCAmelCase_ : Tuple = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) UpperCAmelCase_ : int = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(lowercase_ , lowercase_ , lowercase_ ): return model.decode( decoder_input_ids=lowercase_ , decoder_attention_mask=lowercase_ , encoder_outputs=lowercase_ , ) with self.subTest("JIT Enabled" ): UpperCAmelCase_ : str = decode_jitted(**lowercase_ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): UpperCAmelCase_ : List[Any] = decode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_class_name in self.all_model_classes: UpperCAmelCase_ : Optional[Any] = model_class_name.from_pretrained("facebook/blenderbot_small-90M" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids UpperCAmelCase_ : List[str] = np.ones((1, 1) ) * model.config.eos_token_id UpperCAmelCase_ : Optional[int] = model(lowercase_ ) self.assertIsNotNone(lowercase_ )
61
"""simple docstring""" from __future__ import annotations import requests def _snake_case ( snake_case__ : str ): A = F'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case__ ).json() def _snake_case ( snake_case__ : int = 10 ): A = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' A = requests.get(snake_case__ ).json()[:max_stories] return [get_hackernews_story(snake_case__ ) for story_id in story_ids] def _snake_case ( snake_case__ : int = 10 ): A = hackernews_top_stories(snake_case__ ) return "\n".join('* [{title}]({url})'.format(**snake_case__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
74
0
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
"""simple docstring""" from string import ascii_uppercase _lowercase = {char: i for i, char in enumerate(ascii_uppercase)} _lowercase = dict(enumerate(ascii_uppercase)) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = len(snake_case__ ) A = 0 while True: if x == i: A = 0 if len(snake_case__ ) == len(snake_case__ ): break key += key[i] i += 1 return key def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in message: if letter == " ": cipher_text += " " else: A = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: A = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _snake_case ( ): A = 'THE GERMAN ATTACK' A = 'SECRET' A = generate_key(snake_case__ , snake_case__ ) A = cipher_text(snake_case__ , snake_case__ ) print(F'Encrypted Text = {s}' ) print(F'Original Text = {original_text(snake_case__ , snake_case__ )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
74
0
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _lowerCamelCase ( lowercase : Union[str, Any] , lowercase : int , lowercase : int=1024 , lowercase : int=1024 , lowercase : Tuple=False , **lowercase : Optional[int] ) -> Union[str, Any]: _a = AutoTokenizer.from_pretrained(lowercase ) _a = SeqaSeqDataset(lowercase , lowercase , lowercase , lowercase , type_path="train" , **lowercase ) _a = tok.pad_token_id def get_lens(lowercase : Optional[int] ): _a = tqdm( DataLoader(lowercase , batch_size=512 , num_workers=8 , shuffle=lowercase , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) _a = [] for batch in dl: _a = batch["input_ids"].ne(lowercase ).sum(1 ).tolist() _a = batch["labels"].ne(lowercase ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowercase , lowercase ): max_lens.append(max(lowercase , lowercase ) ) else: max_lens.extend(lowercase ) return max_lens _a = get_lens(lowercase ) _a = SeqaSeqDataset(lowercase , lowercase , lowercase , lowercase , type_path="val" , **lowercase ) _a = get_lens(lowercase ) pickle_save(lowercase , train_ds.len_file ) pickle_save(lowercase , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
63
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ) -> Optional[Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] ,model_result['ss'] ): A = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = 'sgugger/tiny-distilbert-classification' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,only_pretrain_model=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,torchscript=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,fpaa=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) # set architectures equal to `None` A = None A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' ,'Can\'t do half precision' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,fpaa=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,save_to_csv=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,inference_time_csv_file=os.path.join(A_ ,'inf_time.csv' ) ,train_memory_csv_file=os.path.join(A_ ,'train_mem.csv' ) ,inference_memory_csv_file=os.path.join(A_ ,'inf_mem.csv' ) ,train_time_csv_file=os.path.join(A_ ,'train_time.csv' ) ,env_info_csv_file=os.path.join(A_ ,'env.csv' ) ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) benchmark.run() self.assertTrue(Path(os.path.join(A_ ,'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'env.csv' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(A_ : Optional[int] ): self.assertTrue(hasattr(A_ ,'sequential' ) ) self.assertTrue(hasattr(A_ ,'cumulative' ) ) self.assertTrue(hasattr(A_ ,'current' ) ) self.assertTrue(hasattr(A_ ,'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,log_filename=os.path.join(A_ ,'log.txt' ) ,log_print=A_ ,trace_memory_line_by_line=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A_ ,'log.txt' ) ).exists() )
74
0
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin A_ = get_tests_dir('''fixtures/test_sentencepiece.model''') A_ = get_tests_dir('''fixtures/test_sentencepiece_bpe.model''') A_ = '''pt''' if is_torch_available() else '''tf''' @require_sentencepiece @require_tokenizers class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = CamembertTokenizer lowercase__ = CamembertTokenizerFast lowercase__ = True lowercase__ = True def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _snake_case : List[str] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : str = """<pad>""" _snake_case : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ), a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ), a_ ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1], """<pad>""" ) self.assertEqual(vocab_keys[-1], """<mask>""" ) self.assertEqual(len(a_ ), 1_004 ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 1_005 ) def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : List[Any] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) _snake_case : Dict = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _snake_case : Dict = """I was born in 92000, and this is falsé.""" _snake_case : List[str] = tokenizer.encode(a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) _snake_case : int = tokenizer.encode(a_, add_special_tokens=a_ ) _snake_case : int = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _snake_case : Any = tokenizer.convert_ids_to_tokens(a_ ) _snake_case : Optional[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return _snake_case : Tuple = self.get_tokenizer() _snake_case : Tuple = self.get_rust_tokenizer() _snake_case : List[Any] = """I was born in 92000, and this is falsé.""" _snake_case : int = tokenizer.tokenize(a_ ) _snake_case : Union[str, Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_, a_ ) _snake_case : Tuple = tokenizer.encode(a_, add_special_tokens=a_ ) _snake_case : Optional[Any] = rust_tokenizer.encode(a_, add_special_tokens=a_ ) self.assertListEqual(a_, a_ ) _snake_case : Any = self.get_rust_tokenizer() _snake_case : List[str] = tokenizer.encode(a_ ) _snake_case : str = rust_tokenizer.encode(a_ ) self.assertListEqual(a_, a_ ) @slow def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Optional[Any] = {"""input_ids""": [[5, 54, 7_196, 297, 30, 23, 776, 18, 11, 3_215, 3_705, 8_252, 22, 3_164, 1_181, 2_116, 29, 16, 813, 25, 791, 3_314, 20, 3_446, 38, 27_575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9_088, 20, 1_517, 8, 22_804, 18_818, 10, 38, 629, 607, 607, 142, 19, 7_196, 867, 56, 10_326, 24, 2_267, 20, 416, 5_072, 15_612, 233, 734, 7, 2_399, 27, 16, 3_015, 1_649, 7, 24, 20, 4_338, 2_399, 27, 13, 3_400, 14, 13, 6_189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _snake_case : List[str] = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=a_, model_name="""camembert-base""", revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""", sequences=a_, )
64
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _lowercase = re.compile(r'''^(?P<major>\d+)''' r'''\.(?P<minor>\d+)''' r'''\.(?P<patch>\d+)$''') @total_ordering @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: A , A , A = _str_to_version_tuple(self.version_str ) def __repr__( self : Optional[int] ) -> Dict: return F'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return self.major, self.minor, self.patch def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Tuple ) -> Union[str, Any]: if isinstance(A_ ,A_ ): return Version(A_ ) elif isinstance(A_ ,A_ ): return other raise TypeError(F'{other} (type {type(A_ )}) cannot be compared to version.' ) def __eq__( self : List[Any] ,A_ : Dict ) -> Any: try: A = self._validate_operand(A_ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : List[Any] ,A_ : Optional[int] ) -> Tuple: A = self._validate_operand(A_ ) return self.tuple < other.tuple def __hash__( self : Union[str, Any] ) -> Union[str, Any]: return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[str] ) -> List[str]: A = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.version_str def _snake_case ( snake_case__ : List[str] ): A = _VERSION_REG.match(snake_case__ ) if not res: raise ValueError(F'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(snake_case__ ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def _snake_case ( snake_case__ : str ): return ".".join(str(snake_case__ ) for v in version_tuple )
74
0
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = 10 UpperCAmelCase__ = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string" ) ), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"] ) ), "answers": datasets.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), "id": datasets.Value("int64" ), } ) UpperCAmelCase__ = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(__A ) ), }, features=__A, ) return dataset @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "file.arrow" ) dataset.map(cache_file_name=__A ) return filename # FILE_CONTENT + files UpperCamelCase__ = '\\n Text data.\n Second line of data.' @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Tuple: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt" UpperCAmelCase__ = FILE_CONTENT with open(__A, "w" ) as f: f.write(__A ) return filename @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' import bza UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt.bz2" UpperCAmelCase__ = bytes(__A, "utf-8" ) with bza.open(__A, "wb" ) as f: f.write(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' import gzip UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "file.txt.gz" ) UpperCAmelCase__ = bytes(__A, "utf-8" ) with gzip.open(__A, "wb" ) as f: f.write(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Tuple: '''simple docstring''' if datasets.config.LZ4_AVAILABLE: import lza.frame UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt.lz4" UpperCAmelCase__ = bytes(__A, "utf-8" ) with lza.frame.open(__A, "wb" ) as f: f.write(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> Tuple: '''simple docstring''' if datasets.config.PY7ZR_AVAILABLE: import pyazr UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt.7z" with pyazr.SevenZipFile(__A, "w" ) as archive: archive.write(__A, arcname=os.path.basename(__A ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> Dict: '''simple docstring''' import tarfile UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt.tar" with tarfile.TarFile(__A, "w" ) as f: f.add(__A, arcname=os.path.basename(__A ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' import lzma UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt.xz" UpperCAmelCase__ = bytes(__A, "utf-8" ) with lzma.open(__A, "wb" ) as f: f.write(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> Tuple: '''simple docstring''' import zipfile UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.basename(__A ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.txt.zst" UpperCAmelCase__ = bytes(__A, "utf-8" ) with zstd.open(__A, "wb" ) as f: f.write(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "file.xml" UpperCAmelCase__ = textwrap.dedent( "\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>" ) with open(__A, "w" ) as f: f.write(__A ) return filename UpperCamelCase__ = [ {'col_1': '0', 'col_2': 0, 'col_3': 0.0}, {'col_1': '1', 'col_2': 1, 'col_3': 1.0}, {'col_1': '2', 'col_2': 2, 'col_3': 2.0}, {'col_1': '3', 'col_2': 3, 'col_3': 3.0}, ] UpperCamelCase__ = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] UpperCamelCase__ = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } UpperCamelCase__ = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] UpperCamelCase__ = [ {'col_1': 's0', 'col_2': 0, 'col_3': 0.0}, {'col_1': 's1', 'col_2': 1, 'col_3': 1.0}, {'col_1': 's2', 'col_2': 2, 'col_3': 2.0}, {'col_1': 's3', 'col_2': 3, 'col_3': 3.0}, ] @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' return DATA_DICT_OF_LISTS @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = datasets.Dataset.from_dict(__A ) UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.arrow" ) dataset.map(cache_file_name=__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Any: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.sqlite" ) with contextlib.closing(sqlitea.connect(__A ) ) as con: UpperCAmelCase__ = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)" ) for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)", tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> List[str]: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.csv" ) with open(__A, "w", newline="" ) as f: UpperCAmelCase__ = csv.DictWriter(__A, fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> str: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset2.csv" ) with open(__A, "w", newline="" ) as f: UpperCAmelCase__ = csv.DictWriter(__A, fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> Dict: '''simple docstring''' import bza UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.csv.bz2" with open(__A, "rb" ) as f: UpperCAmelCase__ = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(__A, "wb" ) as f: f.write(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.basename(__A ) ) f.write(__A, arcname=os.path.basename(__A ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.basename(csv_path.replace(".csv", ".CSV" ) ) ) f.write(__A, arcname=os.path.basename(csva_path.replace(".csv", ".CSV" ) ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.csv.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.join("main_dir", os.path.basename(__A ) ) ) f.write(__A, arcname=os.path.join("main_dir", os.path.basename(__A ) ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.parquet" ) UpperCAmelCase__ = pa.schema( { "col_1": pa.string(), "col_2": pa.intaa(), "col_3": pa.floataa(), } ) with open(__A, "wb" ) as f: UpperCAmelCase__ = pq.ParquetWriter(__A, schema=__A ) UpperCAmelCase__ = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(__A ) )] for k in DATA[0]}, schema=__A ) writer.write_table(__A ) writer.close() return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Any: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) UpperCAmelCase__ = {"data": DATA} with open(__A, "w" ) as f: json.dump(__A, __A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) UpperCAmelCase__ = {"data": DATA_DICT_OF_LISTS} with open(__A, "w" ) as f: json.dump(__A, __A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Any: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl" ) with open(__A, "w" ) as f: for item in DATA: f.write(json.dumps(__A ) + "\n" ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset2.jsonl" ) with open(__A, "w" ) as f: for item in DATA: f.write(json.dumps(__A ) + "\n" ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> int: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset_312.jsonl" ) with open(__A, "w" ) as f: for item in DATA_312: f.write(json.dumps(__A ) + "\n" ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> str: '''simple docstring''' UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset-str.jsonl" ) with open(__A, "w" ) as f: for item in DATA_STR: f.write(json.dumps(__A ) + "\n" ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> List[str]: '''simple docstring''' import gzip UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.txt.gz" ) with open(__A, "rb" ) as orig_file: with gzip.open(__A, "wb" ) as zipped_file: zipped_file.writelines(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> Tuple: '''simple docstring''' import gzip UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl.gz" ) with open(__A, "rb" ) as orig_file: with gzip.open(__A, "wb" ) as zipped_file: zipped_file.writelines(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.basename(__A ) ) f.write(__A, arcname=os.path.basename(__A ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A, __A ) -> Any: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.join("nested", os.path.basename(__A ) ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.join("main_dir", os.path.basename(__A ) ) ) f.write(__A, arcname=os.path.join("main_dir", os.path.basename(__A ) ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Any: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.tar" with tarfile.TarFile(__A, "w" ) as f: f.add(__A, arcname=os.path.basename(__A ) ) f.add(__A, arcname=os.path.basename(__A ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A, __A ) -> List[str]: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.tar" with tarfile.TarFile(__A, "w" ) as f: f.add(__A, arcname=os.path.join("nested", os.path.basename(__A ) ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> int: '''simple docstring''' UpperCAmelCase__ = ["0", "1", "2", "3"] UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset.txt" ) with open(__A, "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = ["0", "1", "2", "3"] UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset2.txt" ) with open(__A, "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = ["0", "1", "2", "3"] UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.abc" with open(__A, "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> int: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.text.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.basename(__A ) ) f.write(__A, arcname=os.path.basename(__A ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.text.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.join("main_dir", os.path.basename(__A ) ) ) f.write(__A, arcname=os.path.join("main_dir", os.path.basename(__A ) ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A, __A ) -> Tuple: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.ext.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.basename("unsupported.ext" ) ) f.write(__A, arcname=os.path.basename("unsupported_2.ext" ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = "\n".join(["First", "Second\u2029with Unicode new line", "Third"] ) UpperCAmelCase__ = str(tmp_path_factory.mktemp("data" ) / "dataset_with_unicode_new_lines.txt" ) with open(__A, "w", encoding="utf-8" ) as f: f.write(__A ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' return os.path.join("tests", "features", "data", "test_image_rgb.jpg" ) @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( ) -> List[str]: '''simple docstring''' return os.path.join("tests", "features", "data", "test_audio_44100.wav" ) @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A, __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data" ) / "dataset.img.zip" with zipfile.ZipFile(__A, "w" ) as f: f.write(__A, arcname=os.path.basename(__A ) ) f.write(__A, arcname=os.path.basename(__A ).replace(".jpg", "2.jpg" ) ) return path @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = tmp_path_factory.mktemp("data_dir" ) (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt", "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / "subdir" / "test.txt", "w" ) as f: f.write("bar\n" * 10 ) # hidden file with open(data_dir / "subdir" / ".test.txt", "w" ) as f: f.write("bar\n" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt", "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / ".subdir" / "test.txt", "w" ) as f: f.write("bar\n" * 10 ) return data_dir
65
"""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 _lowercase = NewType('''DataClass''', Any) _lowercase = NewType('''DataClassType''', Any) def _snake_case ( snake_case__ : Tuple ): if isinstance(snake_case__ , snake_case__ ): 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 _snake_case ( snake_case__ : list ): A = {str(snake_case__ ): choice for choice in choices} return lambda snake_case__ : str_to_choice.get(snake_case__ , snake_case__ ) def _snake_case ( *, snake_case__ : Union[str, List[str]] = None , snake_case__ : str = None , snake_case__ : Any = dataclasses.MISSING , snake_case__ : Callable[[], Any] = dataclasses.MISSING , snake_case__ : dict = None , **snake_case__ : Any , ): if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls A = {} if aliases is not None: A = aliases if help is not None: A = help return dataclasses.field(metadata=snake_case__ , default=snake_case__ , default_factory=snake_case__ , **snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Iterable[DataClassType] def __init__( self : List[str] ,A_ : Union[DataClassType, Iterable[DataClassType]] ,**A_ : Any ) -> Optional[int]: # To make the default appear when using --help if "formatter_class" not in kwargs: A = ArgumentDefaultsHelpFormatter super().__init__(**A_ ) if dataclasses.is_dataclass(A_ ): A = [dataclass_types] A = list(A_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ,A_ : dataclasses.Field ) -> Optional[Any]: A = F'--{field.name}' A = 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 ,A_ ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) A = kwargs.pop('aliases' ,[] ) if isinstance(A_ ,A_ ): A = [aliases] A = getattr(field.type ,'__origin__' ,field.type ) if origin_type is Union or (hasattr(A_ ,'UnionType' ) and isinstance(A_ ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A_ ) 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(A_ ) not in field.type.__args__: # filter `str` in Union A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] A = getattr(field.type ,'__origin__' ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) A = ( field.type.__args__[0] if isinstance(A_ ,field.type.__args__[1] ) else field.type.__args__[1] ) A = 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) A = {} if origin_type is Literal or (isinstance(field.type ,A_ ) and issubclass(field.type ,A_ )): if origin_type is Literal: A = field.type.__args__ else: A = [x.value for x in field.type] A = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: A = field.default else: A = 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 A = copy(A_ ) # Hack because type=bool in argparse does not behave as we want. A = 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. A = 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 A = default # This tells argparse we accept 0 or 1 value after --field_name A = '?' # This is the value that will get picked if we do --field_name (without value) A = True elif isclass(A_ ) and issubclass(A_ ,A_ ): A = field.type.__args__[0] A = '+' if field.default_factory is not dataclasses.MISSING: A = field.default_factory() elif field.default is dataclasses.MISSING: A = True else: A = field.type if field.default is not dataclasses.MISSING: A = field.default elif field.default_factory is not dataclasses.MISSING: A = field.default_factory() else: A = True parser.add_argument(A_ ,*A_ ,**A_ ) # 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]): A = False parser.add_argument(F'--no_{field.name}' ,action='store_false' ,dest=field.name ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : DataClassType ) -> List[Any]: if hasattr(A_ ,'_argument_group_name' ): A = self.add_argument_group(dtype._argument_group_name ) else: A = self try: A = get_type_hints(A_ ) 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(A_ ): A = '.'.join(map(A_ ,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(A_ ): if not field.init: continue A = type_hints[field.name] self._parse_dataclass_field(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Any=None ,A_ : int=False ,A_ : Any=True ,A_ : List[str]=None ,A_ : Union[str, Any]=None ,) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): A = [] if args_filename: args_files.append(Path(A_ ) ) 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 A = ArgumentParser() args_file_parser.add_argument(A_ ,type=A_ ,action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) A , A = args_file_parser.parse_known_args(args=A_ ) A = vars(A_ ).get(args_file_flag.lstrip('-' ) ,A_ ) if cmd_args_file_paths: args_files.extend([Path(A_ ) for p in cmd_args_file_paths] ) A = [] 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 A = file_args + args if args is not None else file_args + sys.argv[1:] A , A = self.parse_known_args(args=A_ ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in vars(A_ ).items() if k in keys} for k in keys: delattr(A_ ,A_ ) A = dtype(**A_ ) outputs.append(A_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A_ ) 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 _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Dict[str, Any] ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = set(args.keys() ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) A = dtype(**A_ ) outputs.append(A_ ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(A_ )}' ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: with open(Path(A_ ) ,encoding='utf-8' ) as open_json_file: A = json.loads(open_json_file.read() ) A = self.parse_dict(A_ ,allow_extra_keys=A_ ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = self.parse_dict(yaml.safe_load(Path(A_ ).read_text() ) ,allow_extra_keys=A_ ) return tuple(A_ )
74
0
"""simple docstring""" from math import factorial class lowerCamelCase : '''simple docstring''' def __init__( self: Optional[int] , snake_case: Dict , snake_case: int ) -> Tuple: snake_case_ :List[Any] = real if isinstance(snake_case , snake_case ): snake_case_ :Tuple = [1] * rank else: snake_case_ :Optional[Any] = rank def __repr__( self: List[str] ) -> Tuple: return ( f"""{self.real}+""" f"""{'+'.join(str(snake_case )+'E'+str(n+1 )for n,dual in enumerate(self.duals ) )}""" ) def lowerCAmelCase_ ( self: Optional[int] ) -> Optional[int]: snake_case_ :Any = self.duals.copy() while cur[-1] == 0: cur.pop(-1 ) return Dual(self.real , snake_case ) def __add__( self: Optional[int] , snake_case: Dict ) -> List[str]: if not isinstance(snake_case , snake_case ): return Dual(self.real + other , self.duals ) snake_case_ :List[Any] = self.duals.copy() snake_case_ :Tuple = other.duals.copy() if len(snake_case ) > len(snake_case ): o_dual.extend([1] * (len(snake_case ) - len(snake_case )) ) elif len(snake_case ) < len(snake_case ): s_dual.extend([1] * (len(snake_case ) - len(snake_case )) ) snake_case_ :Dict = [] for i in range(len(snake_case ) ): new_duals.append(s_dual[i] + o_dual[i] ) return Dual(self.real + other.real , snake_case ) _A : str = __add__ def __sub__( self: Tuple , snake_case: Union[str, Any] ) -> Tuple: return self + other * -1 def __mul__( self: str , snake_case: Tuple ) -> Optional[Any]: if not isinstance(snake_case , snake_case ): snake_case_ :Dict = [] for i in self.duals: new_duals.append(i * other ) return Dual(self.real * other , snake_case ) snake_case_ :int = [0] * (len(self.duals ) + len(other.duals ) + 1) for i, item in enumerate(self.duals ): for j, jtem in enumerate(other.duals ): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals ) ): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals ) ): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real , snake_case ) _A : int = __mul__ def __truediv__( self: List[str] , snake_case: List[str] ) -> List[str]: if not isinstance(snake_case , snake_case ): snake_case_ :Optional[Any] = [] for i in self.duals: new_duals.append(i / other ) return Dual(self.real / other , snake_case ) raise ValueError def __floordiv__( self: int , snake_case: List[Any] ) -> Any: if not isinstance(snake_case , snake_case ): snake_case_ :Optional[int] = [] for i in self.duals: new_duals.append(i // other ) return Dual(self.real // other , snake_case ) raise ValueError def __pow__( self: Optional[Any] , snake_case: Optional[int] ) -> List[Any]: if n < 0 or isinstance(snake_case , snake_case ): raise ValueError("""power must be a positive integer""" ) if n == 0: return 1 if n == 1: return self snake_case_ :str = self for _ in range(n - 1 ): x *= self return x def A_ ( _lowercase, _lowercase, _lowercase ): '''simple docstring''' if not callable(_lowercase ): raise ValueError("""differentiate() requires a function as input for func""" ) if not isinstance(_lowercase, (float, int) ): raise ValueError("""differentiate() requires a float as input for position""" ) if not isinstance(_lowercase, _lowercase ): raise ValueError("""differentiate() requires an int as input for order""" ) snake_case_ :Optional[Any] = Dual(_lowercase, 1 ) snake_case_ :List[Any] = func(_lowercase ) if order == 0: return result.real return result.duals[order - 1] * factorial(_lowercase ) if __name__ == "__main__": import doctest doctest.testmod() def A_ ( _lowercase ): '''simple docstring''' return y**2 * y**4 print(differentiate(f, 9, 2))
66
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Dict ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : int ): # 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(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Optional[int] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
74
0
'''simple docstring''' from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __UpperCAmelCase =logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class a__ ( UpperCAmelCase__ ): def __init__( self : str , **a : List[Any] ): """simple docstring""" super().__init__(**a ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING ) def __call__( self : Dict , a : Union[str, List[str], "Image", List["Image"]] , **a : Dict ): """simple docstring""" return super().__call__(a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , **a : Optional[Any] ): """simple docstring""" __lowerCamelCase = {} if "candidate_labels" in kwargs: __lowerCamelCase = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __lowerCamelCase = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : str , a : Dict=None , a : Any="This is a photo of {}." ): """simple docstring""" __lowerCamelCase = load_image(a ) __lowerCamelCase = self.image_processor(images=[image] , return_tensors=self.framework ) __lowerCamelCase = candidate_labels __lowerCamelCase = [hypothesis_template.format(a ) for x in candidate_labels] __lowerCamelCase = self.tokenizer(a , return_tensors=self.framework , padding=a ) __lowerCamelCase = [text_inputs] return inputs def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = model_inputs.pop('''candidate_labels''' ) __lowerCamelCase = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , a ): __lowerCamelCase = text_inputs[0] else: # Batching case. __lowerCamelCase = text_inputs[0][0] __lowerCamelCase = self.model(**a , **a ) __lowerCamelCase = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Dict , a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = model_outputs.pop('''candidate_labels''' ) __lowerCamelCase = model_outputs['''logits'''][0] if self.framework == "pt": __lowerCamelCase = logits.softmax(dim=-1 ).squeeze(-1 ) __lowerCamelCase = probs.tolist() if not isinstance(a , a ): __lowerCamelCase = [scores] elif self.framework == "tf": __lowerCamelCase = stable_softmax(a , axis=-1 ) __lowerCamelCase = probs.numpy().tolist() else: raise ValueError(f"""Unsupported framework: {self.framework}""" ) __lowerCamelCase = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(a , a ) , key=lambda a : -x[0] ) ] return result
67
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
0
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
68
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase = logging.get_logger(__name__) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : int ,**A_ : Any ) -> Any: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A = deprecated_arg[3:] A = not kwargs.pop(A_ ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) A = kwargs.pop('tpu_name' ,self.tpu_name ) A = kwargs.pop('device_idx' ,self.device_idx ) A = kwargs.pop('eager_mode' ,self.eager_mode ) A = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**A_ ) _lowerCamelCase: str = field( default=_lowercase , metadata={'''help''': '''Name of TPU'''} , ) _lowerCamelCase: int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) _lowerCamelCase: bool = field(default=_lowercase , metadata={'''help''': '''Benchmark models in eager model.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) A = None if self.tpu: try: if self.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: A = None return tpu @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) A = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) A = tf.distribute.OneDeviceStrategy(device=F'/gpu:{self.device_idx}' ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU A = tf.distribute.OneDeviceStrategy(device=F'/cpu:{self.device_idx}' ) return strategy @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def _SCREAMING_SNAKE_CASE ( self : int ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _SCREAMING_SNAKE_CASE ( self : str ) -> bool: return self.n_gpu > 0
74
0
"""simple docstring""" import math import sys def UpperCAmelCase ( UpperCAmelCase ) -> int: if number != int(UpperCAmelCase ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 snake_case_ = [-1] * (number + 1) snake_case_ = 0 for i in range(1 , number + 1 ): snake_case_ = sys.maxsize snake_case_ = int(math.sqrt(UpperCAmelCase ) ) for j in range(1 , root + 1 ): snake_case_ = 1 + answers[i - (j**2)] snake_case_ = min(UpperCAmelCase , UpperCAmelCase ) snake_case_ = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
69
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowercase = logging.get_logger(__name__) _lowercase = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''dpt''' def __init__( self : str ,A_ : Tuple=768 ,A_ : int=12 ,A_ : Optional[int]=12 ,A_ : Optional[int]=3072 ,A_ : List[str]="gelu" ,A_ : str=0.0 ,A_ : int=0.0 ,A_ : str=0.02 ,A_ : str=1e-12 ,A_ : str=384 ,A_ : Dict=16 ,A_ : Union[str, Any]=3 ,A_ : Dict=False ,A_ : Any=True ,A_ : Optional[int]=[2, 5, 8, 11] ,A_ : Optional[Any]="project" ,A_ : Tuple=[4, 2, 1, 0.5] ,A_ : int=[96, 192, 384, 768] ,A_ : int=256 ,A_ : str=-1 ,A_ : Optional[int]=False ,A_ : Optional[int]=True ,A_ : Union[str, Any]=0.4 ,A_ : Union[str, Any]=255 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=[1, 1024, 24, 24] ,A_ : List[str]=[0, 1] ,A_ : List[Any]=None ,**A_ : Tuple ,) -> Union[str, Any]: super().__init__(**A_ ) A = hidden_size A = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): logger.info('Initializing the config with a `BiT` backbone.' ) A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): A = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) A = backbone_featmap_shape A = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: A = None A = None A = [] A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) A = readout_type A = reassemble_factors A = neck_hidden_sizes A = fusion_hidden_size A = head_in_index A = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) A = use_auxiliary_head A = auxiliary_loss_weight A = semantic_loss_ignore_index A = semantic_classifier_dropout def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: A = self.backbone_config.to_dict() A = self.__class__.model_type return output
74
0
'''simple docstring''' A__ : str =[ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = [False] * len(lowerCAmelCase ) _lowerCAmelCase = [s] _lowerCAmelCase = True while queue: _lowerCAmelCase = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(lowerCAmelCase ) _lowerCAmelCase = True _lowerCAmelCase = u return visited[t] def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = [-1] * (len(lowerCAmelCase )) _lowerCAmelCase = 0 _lowerCAmelCase = [] _lowerCAmelCase = [i[:] for i in graph] # Record original cut, copy. while bfs(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): _lowerCAmelCase = float("""Inf""" ) _lowerCAmelCase = sink while s != source: # Find the minimum value in select path _lowerCAmelCase = min(lowerCAmelCase , graph[parent[s]][s] ) _lowerCAmelCase = parent[s] max_flow += path_flow _lowerCAmelCase = sink while v != source: _lowerCAmelCase = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _lowerCAmelCase = parent[v] for i in range(len(lowerCAmelCase ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
70
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
0
import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __A : """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=30 , lowerCamelCase__=2 , lowerCamelCase__=3 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=32 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=10 , lowerCamelCase__=0.02 , lowerCamelCase__=None , lowerCamelCase__=2 , ): """simple docstring""" __UpperCamelCase : Optional[Any] =parent __UpperCamelCase : Union[str, Any] =batch_size __UpperCamelCase : List[str] =image_size __UpperCamelCase : int =patch_size __UpperCamelCase : Optional[int] =num_channels __UpperCamelCase : Optional[Any] =is_training __UpperCamelCase : List[str] =use_labels __UpperCamelCase : List[Any] =hidden_size __UpperCamelCase : Union[str, Any] =num_hidden_layers __UpperCamelCase : Any =num_attention_heads __UpperCamelCase : int =intermediate_size __UpperCamelCase : Tuple =hidden_act __UpperCamelCase : Tuple =hidden_dropout_prob __UpperCamelCase : Dict =attention_probs_dropout_prob __UpperCamelCase : List[str] =type_sequence_label_size __UpperCamelCase : Union[str, Any] =initializer_range __UpperCamelCase : Union[str, Any] =scope __UpperCamelCase : List[str] =encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __UpperCamelCase : Tuple =(image_size // patch_size) ** 2 __UpperCamelCase : int =num_patches + 1 def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Any =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCamelCase : str =None if self.use_labels: __UpperCamelCase : str =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase : List[str] =self.get_config() return config, pixel_values, labels def __lowercase ( self ): """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=lowerCamelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : List[Any] =ViTModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCamelCase : Optional[Any] =model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Union[str, Any] =ViTForMaskedImageModeling(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCamelCase : Union[str, Any] =model(lowerCamelCase__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCamelCase : Optional[Any] =1 __UpperCamelCase : List[str] =ViTForMaskedImageModeling(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCamelCase : Union[str, Any] =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCamelCase : Optional[int] =model(lowerCamelCase__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Optional[int] =self.type_sequence_label_size __UpperCamelCase : Union[str, Any] =ViTForImageClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCamelCase : Any =model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __UpperCamelCase : int =1 __UpperCamelCase : str =ViTForImageClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCamelCase : Optional[Any] =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCamelCase : List[Any] =model(lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[Any] =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) : Any =config_and_inputs __UpperCamelCase : str ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class __A ( a , a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : Tuple =( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) UpperCamelCase__ : Optional[int] =( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) UpperCamelCase__ : Any =True UpperCamelCase__ : Tuple =False UpperCamelCase__ : List[str] =False UpperCamelCase__ : str =False def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =ViTModelTester(self ) __UpperCamelCase : List[str] =ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=37 ) def __lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds' ) def __lowercase ( self ): """simple docstring""" pass def __lowercase ( self ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : int =model_class(lowerCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCamelCase : Union[str, Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase__ , nn.Linear ) ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Any =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : List[str] =model_class(lowerCamelCase__ ) __UpperCamelCase : List[Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase : Optional[Any] =[*signature.parameters.keys()] __UpperCamelCase : str =['pixel_values'] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Union[str, Any] =ViTModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def A ( ) -> Union[str, Any]: __UpperCamelCase : int =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __A ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self ): """simple docstring""" return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224' ) if is_vision_available() else None @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : int =ViTForImageClassification.from_pretrained('google/vit-base-patch16-224' ).to(lowerCamelCase__ ) __UpperCamelCase : Optional[int] =self.default_image_processor __UpperCamelCase : List[str] =prepare_img() __UpperCamelCase : Optional[int] =image_processor(images=lowerCamelCase__ , return_tensors='pt' ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): __UpperCamelCase : int =model(**lowerCamelCase__ ) # verify the logits __UpperCamelCase : Any =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) __UpperCamelCase : Optional[Any] =torch.tensor([-0.2_744, 0.8_215, -0.0_836] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase__ , atol=1E-4 ) ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : int =ViTModel.from_pretrained('facebook/dino-vits8' ).to(lowerCamelCase__ ) __UpperCamelCase : Optional[Any] =ViTImageProcessor.from_pretrained('facebook/dino-vits8' , size=480 ) __UpperCamelCase : Optional[Any] =prepare_img() __UpperCamelCase : Any =image_processor(images=lowerCamelCase__ , return_tensors='pt' ) __UpperCamelCase : int =inputs.pixel_values.to(lowerCamelCase__ ) # forward pass with torch.no_grad(): __UpperCamelCase : Any =model(lowerCamelCase__ , interpolate_pos_encoding=lowerCamelCase__ ) # verify the logits __UpperCamelCase : str =torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =torch.tensor( [[4.2_340, 4.3_906, -6.6_692], [4.5_463, 1.8_928, -6.7_257], [4.4_429, 0.8_496, -5.8_585]] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase__ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase ( self ): """simple docstring""" __UpperCamelCase : int =ViTModel.from_pretrained('facebook/dino-vits8' , torch_dtype=torch.floataa , device_map='auto' ) __UpperCamelCase : Optional[int] =self.default_image_processor __UpperCamelCase : Dict =prepare_img() __UpperCamelCase : List[Any] =image_processor(images=lowerCamelCase__ , return_tensors='pt' ) __UpperCamelCase : List[str] =inputs.pixel_values.to(lowerCamelCase__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __UpperCamelCase : List[Any] =model(lowerCamelCase__ )
71
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ,A_ : int ) -> Union[str, Any]: A = n A = [None] * self.n A = 0 # index of the first element A = 0 A = 0 def __len__( self : int ) -> int: return self.size def _SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.size == 0 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: return False if self.is_empty() else self.array[self.front] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ) -> int: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A = data A = (self.rear + 1) % self.n self.size += 1 return self def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) A = self.array[self.front] A = None A = (self.front + 1) % self.n self.size -= 1 return temp
74
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,*A_ : List[str] ,**A_ : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' ,A_ ,) super().__init__(*A_ ,**A_ )
74
0
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''gpt_bigcode''' _lowerCamelCase: List[Any] = ['''past_key_values'''] _lowerCamelCase: int = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Optional[int] ,A_ : Dict=5_0257 ,A_ : Union[str, Any]=1024 ,A_ : str=768 ,A_ : Any=12 ,A_ : Any=12 ,A_ : Optional[int]=None ,A_ : Any="gelu_pytorch_tanh" ,A_ : List[str]=0.1 ,A_ : Optional[int]=0.1 ,A_ : List[str]=0.1 ,A_ : Tuple=1e-5 ,A_ : Optional[int]=0.02 ,A_ : List[str]=True ,A_ : Optional[Any]=True ,A_ : List[Any]=5_0256 ,A_ : Union[str, Any]=5_0256 ,A_ : int=True ,A_ : Optional[Any]=True ,A_ : Dict=True ,**A_ : Union[str, Any] ,) -> Union[str, Any]: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = scale_attn_weights A = use_cache A = attention_softmax_in_fpaa A = scale_attention_softmax_in_fpaa A = multi_query A = bos_token_id A = eos_token_id super().__init__(bos_token_id=A_ ,eos_token_id=A_ ,**A_ )
74
0
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets a_ : Optional[Any] = """\ @inproceedings{popovic-2015-chrf, title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\", author = \"Popovi{\'c}, Maja\", booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\", month = sep, year = \"2015\", address = \"Lisbon, Portugal\", publisher = \"Association for Computational Linguistics\", url = \"https://aclanthology.org/W15-3049\", doi = \"10.18653/v1/W15-3049\", pages = \"392--395\", } @inproceedings{popovic-2017-chrf, title = \"chr{F}++: words helping character n-grams\", author = \"Popovi{\'c}, Maja\", booktitle = \"Proceedings of the Second Conference on Machine Translation\", month = sep, year = \"2017\", address = \"Copenhagen, Denmark\", publisher = \"Association for Computational Linguistics\", url = \"https://aclanthology.org/W17-4770\", doi = \"10.18653/v1/W17-4770\", pages = \"612--618\", } @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ a_ : List[Any] = """\ ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches, and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation that is already present in sacrebleu. The implementation here is slightly different from sacrebleu in terms of the required input format. The length of the references and hypotheses lists need to be the same, so you may need to transpose your references compared to sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534 See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information. """ a_ : Optional[Any] = """ Produces ChrF(++) scores for hypotheses given reference translations. Args: predictions (list of str): The predicted sentences. references (list of list of str): The references. There should be one reference sub-list for each prediction sentence. char_order (int): Character n-gram order. Defaults to `6`. word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`. beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`. lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`. whitespace (bool): If `True`, include whitespaces when extracting character n-grams. eps_smoothing (bool): If `True`, applies epsilon smoothing similar to reference chrF++.py, NLTK and Moses implementations. If `False`, it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`. Returns: 'score' (float): The chrF (chrF++) score, 'char_order' (int): The character n-gram order, 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++, 'beta' (int): Determine the importance of recall w.r.t precision Examples: Example 1--a simple example of calculating chrF: >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"] >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]] >>> chrf = datasets.load_metric(\"chrf\") >>> results = chrf.compute(predictions=prediction, references=reference) >>> print(results) {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2} Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF: >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"] >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]] >>> chrf = datasets.load_metric(\"chrf\") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2) >>> print(results) {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2} Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case: >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"] >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]] >>> chrf = datasets.load_metric(\"chrf\") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2, ... lowercase=True) >>> print(results) {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def lowercase__ ( self ): """simple docstring""" if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''', id='''sequence''' ), id='''references''' ), } ), codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''], reference_urls=[ '''https://github.com/m-popovic/chrF''', ], ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = CHRF.CHAR_ORDER, lowerCAmelCase = CHRF.WORD_ORDER, lowerCAmelCase = CHRF.BETA, lowerCAmelCase = False, lowerCAmelCase = False, lowerCAmelCase = False, ): """simple docstring""" lowerCamelCase_ =len(references[0] ) if any(len(lowerCAmelCase ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) lowerCamelCase_ =[[refs[i] for refs in references] for i in range(lowerCAmelCase )] lowerCamelCase_ =CHRF(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ) lowerCamelCase_ =sb_chrf.corpus_score(lowerCAmelCase, lowerCAmelCase ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
75
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
0
import os a_ = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : Any = 0 while index < len(_a) - 1: SCREAMING_SNAKE_CASE : List[str] = SYMBOLS[numerals[index]] SCREAMING_SNAKE_CASE : int = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Any = "" SCREAMING_SNAKE_CASE : List[Any] = num // 1000 numerals += m_count * "M" num %= 1000 SCREAMING_SNAKE_CASE : List[Any] = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 SCREAMING_SNAKE_CASE : str = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def lowerCamelCase__ ( _a = "/p089_roman.txt"): SCREAMING_SNAKE_CASE : List[str] = 0 with open(os.path.dirname(_a) + roman_numerals_filename) as filea: SCREAMING_SNAKE_CASE : Optional[int] = filea.readlines() for line in lines: SCREAMING_SNAKE_CASE : Optional[Any] = line.strip() SCREAMING_SNAKE_CASE : List[str] = parse_roman_numerals(_a) SCREAMING_SNAKE_CASE : List[Any] = generate_roman_numerals(_a) savings += len(_a) - len(_a) return savings if __name__ == "__main__": print(F'''{solution() = }''')
76
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
0
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class UpperCAmelCase_ : def __init__( self , a , a=1_3 , a=7 , a=True , a=True , a=False , a=True , a=9_9 , a=3_2 , a=5 , a=4 , a=3_7 , a="gelu" , a=0.1 , a=0.1 , a=5_1_2 , a=1_6 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, Any]: lowercase__ : Any = parent lowercase__ : List[str] = batch_size lowercase__ : str = seq_length lowercase__ : Optional[Any] = is_training lowercase__ : Tuple = use_input_mask lowercase__ : List[Any] = use_token_type_ids lowercase__ : Dict = use_labels lowercase__ : List[str] = vocab_size lowercase__ : Tuple = hidden_size lowercase__ : Optional[Any] = num_hidden_layers lowercase__ : str = num_attention_heads lowercase__ : Union[str, Any] = intermediate_size lowercase__ : Optional[int] = hidden_act lowercase__ : Optional[Any] = hidden_dropout_prob lowercase__ : Optional[int] = attention_probs_dropout_prob lowercase__ : List[Any] = max_position_embeddings lowercase__ : Optional[Any] = type_vocab_size lowercase__ : Optional[int] = type_sequence_label_size lowercase__ : str = initializer_range lowercase__ : Tuple = num_labels lowercase__ : int = num_choices lowercase__ : Union[str, Any] = scope def _UpperCAmelCase ( self ) -> Any: lowercase__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ : List[str] = None if self.use_input_mask: lowercase__ : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ : Dict = None if self.use_token_type_ids: lowercase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase__ : Tuple = None lowercase__ : Tuple = None lowercase__ : Tuple = None if self.use_labels: lowercase__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) lowercase__ : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCAmelCase ( self ) -> str: return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , ) def _UpperCAmelCase ( self , a , a , a , a , a , a , a ) -> Optional[Any]: lowercase__ : int = LlamaModel(config=a ) model.to(a ) model.eval() lowercase__ : Union[str, Any] = model(a , attention_mask=a ) lowercase__ : int = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCAmelCase ( self , a , a , a , a , a , a , a , a , a , ) -> Any: lowercase__ : Union[str, Any] = True lowercase__ : Tuple = LlamaModel(a ) model.to(a ) model.eval() lowercase__ : Any = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) lowercase__ : Dict = model( a , attention_mask=a , encoder_hidden_states=a , ) lowercase__ : int = model(a , attention_mask=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCAmelCase ( self , a , a , a , a , a , a , a , a , a , ) -> Optional[Any]: lowercase__ : Dict = LlamaForCausalLM(config=a ) model.to(a ) model.eval() lowercase__ : Optional[Any] = model(a , attention_mask=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCAmelCase ( self , a , a , a , a , a , a , a , a , a , ) -> Union[str, Any]: lowercase__ : Any = True lowercase__ : List[Any] = True lowercase__ : Union[str, Any] = LlamaForCausalLM(config=a ) model.to(a ) model.eval() # first forward pass lowercase__ : Optional[Any] = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) lowercase__ : int = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowercase__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowercase__ : Optional[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowercase__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase__ : Tuple = torch.cat([input_mask, next_mask] , dim=-1 ) lowercase__ : Tuple = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] lowercase__ : Optional[int] = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice lowercase__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase__ : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() lowercase__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1e-3 ) ) def _UpperCAmelCase ( self ) -> int: lowercase__ : Dict = self.prepare_config_and_inputs() ( ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ( lowercase__ ) , ) : Dict = config_and_inputs lowercase__ : Any = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _a , _a , _a , unittest.TestCase): lowerCamelCase__ : Any = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () lowerCamelCase__ : List[Any] = (LlamaForCausalLM,) if is_torch_available() else () lowerCamelCase__ : str = ( { "feature-extraction": LlamaModel, "text-classification": LlamaForSequenceClassification, "text-generation": LlamaForCausalLM, "zero-shot": LlamaForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ : Tuple = False lowerCamelCase__ : str = False def _UpperCAmelCase ( self ) -> Dict: lowercase__ : Tuple = LlamaModelTester(self ) lowercase__ : List[Any] = ConfigTester(self , config_class=a , hidden_size=3_7 ) def _UpperCAmelCase ( self ) -> int: self.config_tester.run_common_tests() def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowercase__ : Any = type self.model_tester.create_and_check_model(*a ) def _UpperCAmelCase ( self ) -> int: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Tuple = 3 lowercase__ : str = input_dict['input_ids'] lowercase__ : str = input_ids.ne(1 ).to(a ) lowercase__ : Tuple = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowercase__ : Optional[int] = LlamaForSequenceClassification(a ) model.to(a ) model.eval() lowercase__ : Tuple = model(a , attention_mask=a , labels=a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCAmelCase ( self ) -> int: lowercase__ , lowercase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Tuple = 3 lowercase__ : str = 'single_label_classification' lowercase__ : int = input_dict['input_ids'] lowercase__ : List[Any] = input_ids.ne(1 ).to(a ) lowercase__ : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowercase__ : Any = LlamaForSequenceClassification(a ) model.to(a ) model.eval() lowercase__ : Dict = model(a , attention_mask=a , labels=a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ , lowercase__ : int = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Union[str, Any] = 3 lowercase__ : str = 'multi_label_classification' lowercase__ : List[str] = input_dict['input_ids'] lowercase__ : Optional[Any] = input_ids.ne(1 ).to(a ) lowercase__ : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) lowercase__ : Any = LlamaForSequenceClassification(a ) model.to(a ) model.eval() lowercase__ : List[Any] = model(a , attention_mask=a , labels=a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def _UpperCAmelCase ( self ) -> Union[str, Any]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def _UpperCAmelCase ( self , a ) -> List[Any]: lowercase__ , lowercase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Optional[int] = ids_tensor([1, 1_0] , config.vocab_size ) lowercase__ : Tuple = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowercase__ : int = LlamaModel(a ) original_model.to(a ) original_model.eval() lowercase__ : int = original_model(a ).last_hidden_state lowercase__ : Optional[int] = original_model(a ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowercase__ : Union[str, Any] = {'type': scaling_type, 'factor': 10.0} lowercase__ : Optional[int] = LlamaModel(a ) scaled_model.to(a ) scaled_model.eval() lowercase__ : str = scaled_model(a ).last_hidden_state lowercase__ : Union[str, Any] = scaled_model(a ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(a , a , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1e-5 ) ) @require_torch class UpperCAmelCase_ ( unittest.TestCase): @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : Dict = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowercase__ : Dict = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) lowercase__ : List[str] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 lowercase__ : Dict = torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]] ) torch.testing.assert_close(out.mean(-1 ) , a , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowercase__ : int = torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , a , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ : Optional[int] = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowercase__ : Optional[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) lowercase__ : Any = model(torch.tensor(a ) ) # Expected mean on dim = -1 lowercase__ : Optional[int] = torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]] ) torch.testing.assert_close(out.mean(-1 ) , a , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowercase__ : Tuple = torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , a , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def _UpperCAmelCase ( self ) -> int: lowercase__ : Optional[Any] = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowercase__ : Union[str, Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) lowercase__ : int = model(torch.tensor(a ) ) # Expected mean on dim = -1 lowercase__ : Tuple = torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]] ) torch.testing.assert_close(out.mean(-1 ) , a , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowercase__ : int = torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , a , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : str = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowercase__ : Optional[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) lowercase__ : Optional[int] = model(torch.tensor(a ) ) lowercase__ : int = torch.tensor( [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , a , atol=1e-2 , rtol=1e-2 ) # fmt: off lowercase__ : Optional[Any] = torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , a , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def _UpperCAmelCase ( self ) -> Any: lowercase__ : str = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' lowercase__ : Optional[int] = 'Simply put, the theory of relativity states that ' lowercase__ : List[Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) lowercase__ : Optional[int] = tokenizer.encode(a , return_tensors='pt' ) lowercase__ : int = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=a ) # greedy generation outputs lowercase__ : str = model.generate(a , max_new_tokens=6_4 , top_p=a , temperature=1 , do_sample=a ) lowercase__ : Optional[Any] = tokenizer.decode(generated_ids[0] , skip_special_tokens=a ) self.assertEqual(a , a )
77
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
0
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _lowerCAmelCase ( lowercase_ = "isbn/0140328726" ): UpperCAmelCase = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: UpperCAmelCase = F"""{olid} is not a valid Open Library olid""" raise ValueError(lowercase_ ) return requests.get(F"""https://openlibrary.org/{new_olid}.json""" ).json() def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = { 'title': 'Title', 'publish_date': 'Publish date', 'authors': 'Authors', 'number_of_pages': 'Number of pages:', 'first_sentence': 'First sentence', 'isbn_10': 'ISBN (10)', 'isbn_13': 'ISBN (13)', } UpperCAmelCase = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} UpperCAmelCase = [ get_openlibrary_data(author['key'] )['name'] for author in data['Authors'] ] UpperCAmelCase = data['First sentence']['value'] for key, value in data.items(): if isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = ', '.join(lowercase_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: snake_case_ = input("""\nEnter the ISBN code to search (or 'quit' to stop): """).strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: snake_case_ = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print("""\n""".join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
78
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : list[int] ) -> None: A = len(A_ ) A = [0] * len_array if len_array > 0: A = array[0] for i in range(1 ,A_ ): A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ) -> bool: A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(A_ ) return False if __name__ == "__main__": import doctest doctest.testmod()
74
0
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, 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 MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class _UpperCAmelCase : """simple docstring""" def __init__( self : str , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : List[Any]=False , __UpperCAmelCase : Any=10 , __UpperCAmelCase : Optional[int]=3 , __UpperCAmelCase : int=32 * 8 , __UpperCAmelCase : int=32 * 8 , __UpperCAmelCase : List[Any]=4 , __UpperCAmelCase : Optional[int]=64 , ): '''simple docstring''' _A = parent _A = batch_size _A = is_training _A = use_auxiliary_loss _A = num_queries _A = num_channels _A = min_size _A = max_size _A = num_labels _A = hidden_dim _A = hidden_dim def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' _A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __UpperCAmelCase ) _A = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__UpperCAmelCase ) _A = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__UpperCAmelCase ) > 0.5 ).float() _A = (torch.rand((self.batch_size, self.num_labels) , device=__UpperCAmelCase ) > 0.5).long() _A = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' _A = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _A = self.num_queries _A = self.num_labels _A = [1, 1, 1, 1] _A = self.num_channels _A = 64 _A = 128 _A = self.hidden_dim _A = self.hidden_dim _A = self.hidden_dim return config def lowerCAmelCase ( self : Tuple ): '''simple docstring''' _A , _A , _A , _A , _A = self.prepare_config_and_inputs() _A = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[int] ): '''simple docstring''' _A = output.encoder_hidden_states _A = output.pixel_decoder_hidden_states _A = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__UpperCAmelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__UpperCAmelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__UpperCAmelCase ) , config.decoder_layers ) def lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str]=False ): '''simple docstring''' with torch.no_grad(): _A = MaskaFormerModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() _A = model(pixel_values=__UpperCAmelCase , pixel_mask=__UpperCAmelCase ) _A = model(__UpperCAmelCase , output_hidden_states=__UpperCAmelCase ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__UpperCAmelCase , __UpperCAmelCase ) def lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any] ): '''simple docstring''' _A = MaskaFormerForUniversalSegmentation(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() def comm_check_on_output(__UpperCAmelCase : 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(): _A = model(pixel_values=__UpperCAmelCase , pixel_mask=__UpperCAmelCase ) _A = model(__UpperCAmelCase ) comm_check_on_output(__UpperCAmelCase ) _A = model( pixel_values=__UpperCAmelCase , pixel_mask=__UpperCAmelCase , mask_labels=__UpperCAmelCase , class_labels=__UpperCAmelCase ) comm_check_on_output(__UpperCAmelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class _UpperCAmelCase ( snake_case_ , snake_case_ , unittest.TestCase ): """simple docstring""" snake_case = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () snake_case = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} snake_case = False snake_case = False snake_case = False snake_case = False def lowerCAmelCase ( self : str ): '''simple docstring''' _A = MaskaFormerModelTester(self ) _A = ConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase ) def lowerCAmelCase ( self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase ( self : str ): '''simple docstring''' _A , _A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase , **__UpperCAmelCase , output_hidden_states=__UpperCAmelCase ) def lowerCAmelCase ( self : str ): '''simple docstring''' _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__UpperCAmelCase ) @unittest.skip(reason="Mask2Former does not use inputs_embeds" ) def lowerCAmelCase ( self : List[str] ): '''simple docstring''' pass @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" ) def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="Mask2Former is not a generative model" ) def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' pass @unittest.skip(reason="Mask2Former does not use token embeddings" ) def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def lowerCAmelCase ( self : List[str] ): '''simple docstring''' pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' pass def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' _A , _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(__UpperCAmelCase ) _A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A = [*signature.parameters.keys()] _A = ["pixel_values"] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) @slow def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _A = MaskaFormerModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def lowerCAmelCase ( self : int ): '''simple docstring''' _A = (self.model_tester.min_size,) * 2 _A = { "pixel_values": torch.randn((2, 3, *size) , device=__UpperCAmelCase ), "mask_labels": torch.randn((2, 10, *size) , device=__UpperCAmelCase ), "class_labels": torch.zeros(2 , 10 , device=__UpperCAmelCase ).long(), } _A = self.model_tester.get_config() _A = MaskaFormerForUniversalSegmentation(__UpperCAmelCase ).to(__UpperCAmelCase ) _A = model(**__UpperCAmelCase ) self.assertTrue(outputs.loss is not None ) def lowerCAmelCase ( self : str ): '''simple docstring''' _A , _A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase , **__UpperCAmelCase , output_hidden_states=__UpperCAmelCase ) def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' _A , _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(__UpperCAmelCase ).to(__UpperCAmelCase ) _A = model(**__UpperCAmelCase , output_attentions=__UpperCAmelCase ) self.assertTrue(outputs.attentions is not None ) def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' if not self.model_tester.is_training: return _A = self.all_model_classes[1] _A , _A , _A , _A , _A = self.model_tester.prepare_config_and_inputs() _A = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.train() _A = model(__UpperCAmelCase , mask_labels=__UpperCAmelCase , class_labels=__UpperCAmelCase ).loss loss.backward() def lowerCAmelCase ( self : Tuple ): '''simple docstring''' _A = self.all_model_classes[1] _A , _A , _A , _A , _A = self.model_tester.prepare_config_and_inputs() _A = True _A = True _A = model_class(__UpperCAmelCase ).to(__UpperCAmelCase ) model.train() _A = model(__UpperCAmelCase , mask_labels=__UpperCAmelCase , class_labels=__UpperCAmelCase ) _A = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _A = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _A = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _A = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__UpperCAmelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) lowerCamelCase_ = 1e-4 def __lowercase ( ) -> Optional[int]: '''simple docstring''' _A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" @cached_property def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def lowerCAmelCase ( self : List[str] ): '''simple docstring''' _A = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__UpperCAmelCase ) _A = self.default_image_processor _A = prepare_img() _A = image_processor(__UpperCAmelCase , return_tensors="pt" ).to(__UpperCAmelCase ) _A = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__UpperCAmelCase , (1, 3, 384, 384) ) with torch.no_grad(): _A = model(**__UpperCAmelCase ) _A = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(__UpperCAmelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __UpperCAmelCase , atol=__UpperCAmelCase ) ) _A = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(__UpperCAmelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __UpperCAmelCase , atol=__UpperCAmelCase ) ) _A = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(__UpperCAmelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __UpperCAmelCase , atol=__UpperCAmelCase ) ) def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' _A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__UpperCAmelCase ).eval() _A = self.default_image_processor _A = prepare_img() _A = image_processor(__UpperCAmelCase , return_tensors="pt" ).to(__UpperCAmelCase ) _A = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__UpperCAmelCase , (1, 3, 384, 384) ) with torch.no_grad(): _A = model(**__UpperCAmelCase ) # masks_queries_logits _A = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _A = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] _A = torch.tensor(__UpperCAmelCase ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __UpperCAmelCase , atol=__UpperCAmelCase ) ) # class_queries_logits _A = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) _A = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __UpperCAmelCase , atol=__UpperCAmelCase ) ) def lowerCAmelCase ( self : Tuple ): '''simple docstring''' _A = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__UpperCAmelCase ).eval() _A = self.default_image_processor _A = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) _A = inputs["pixel_values"].to(__UpperCAmelCase ) _A = [el.to(__UpperCAmelCase ) for el in inputs["mask_labels"]] _A = [el.to(__UpperCAmelCase ) for el in inputs["class_labels"]] with torch.no_grad(): _A = model(**__UpperCAmelCase ) self.assertTrue(outputs.loss is not None )
79
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = RobertaPreLayerNormConfig.from_pretrained( snake_case__ , architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict A = torch.load(hf_hub_download(repo_id=snake_case__ , filename='pytorch_model.bin' ) ) A = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): A = 'roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue A = tensor_value A = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=snake_case__ , config=snake_case__ , state_dict=snake_case__ ) model.save_pretrained(snake_case__ ) # convert tokenizer A = AutoTokenizer.from_pretrained(snake_case__ ) tokenizer.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
74
0
'''simple docstring''' from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , a , a=None , a=20_48 ): UpperCamelCase__ = config.__dict__ UpperCamelCase__ = modal_hidden_size if num_labels: UpperCamelCase__ = num_labels
80
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''roformer''' def __init__( self : Tuple ,A_ : Optional[int]=5_0000 ,A_ : Tuple=None ,A_ : Optional[Any]=768 ,A_ : Dict=12 ,A_ : Optional[int]=12 ,A_ : Union[str, Any]=3072 ,A_ : Dict="gelu" ,A_ : Dict=0.1 ,A_ : List[Any]=0.1 ,A_ : List[Any]=1536 ,A_ : List[str]=2 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : Optional[int]=0 ,A_ : List[str]=False ,A_ : Tuple=True ,**A_ : List[str] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size if embedding_size is None else embedding_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = rotary_value A = use_cache class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
74
0
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : Dict ): A = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : int ): A , A = emb.weight.shape A = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A = emb.weight.data return lin_layer def _snake_case ( snake_case__ : List[str] , snake_case__ : Any="facebook/mbart-large-en-ro" , snake_case__ : Optional[int]=False , snake_case__ : List[str]=False ): A = torch.load(snake_case__ , map_location='cpu' )['model'] remove_ignore_keys_(snake_case__ ) A = state_dict['encoder.embed_tokens.weight'].shape[0] A = MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: A = 'relu' A = state_dict['decoder.embed_tokens.weight'] A = MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: A = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowercase = 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''') _lowercase = parser.parse_args() _lowercase = 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)
74
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys A__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
82
"""simple docstring""" import argparse import struct import unittest class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : bytes ) -> None: A = data # Initialize hash values A = [ 0X6_A_0_9_E_6_6_7, 0XB_B_6_7_A_E_8_5, 0X3_C_6_E_F_3_7_2, 0XA_5_4_F_F_5_3_A, 0X5_1_0_E_5_2_7_F, 0X9_B_0_5_6_8_8_C, 0X1_F_8_3_D_9_A_B, 0X5_B_E_0_C_D_1_9, ] # Initialize round constants A = [ 0X4_2_8_A_2_F_9_8, 0X7_1_3_7_4_4_9_1, 0XB_5_C_0_F_B_C_F, 0XE_9_B_5_D_B_A_5, 0X3_9_5_6_C_2_5_B, 0X5_9_F_1_1_1_F_1, 0X9_2_3_F_8_2_A_4, 0XA_B_1_C_5_E_D_5, 0XD_8_0_7_A_A_9_8, 0X1_2_8_3_5_B_0_1, 0X2_4_3_1_8_5_B_E, 0X5_5_0_C_7_D_C_3, 0X7_2_B_E_5_D_7_4, 0X8_0_D_E_B_1_F_E, 0X9_B_D_C_0_6_A_7, 0XC_1_9_B_F_1_7_4, 0XE_4_9_B_6_9_C_1, 0XE_F_B_E_4_7_8_6, 0X0_F_C_1_9_D_C_6, 0X2_4_0_C_A_1_C_C, 0X2_D_E_9_2_C_6_F, 0X4_A_7_4_8_4_A_A, 0X5_C_B_0_A_9_D_C, 0X7_6_F_9_8_8_D_A, 0X9_8_3_E_5_1_5_2, 0XA_8_3_1_C_6_6_D, 0XB_0_0_3_2_7_C_8, 0XB_F_5_9_7_F_C_7, 0XC_6_E_0_0_B_F_3, 0XD_5_A_7_9_1_4_7, 0X0_6_C_A_6_3_5_1, 0X1_4_2_9_2_9_6_7, 0X2_7_B_7_0_A_8_5, 0X2_E_1_B_2_1_3_8, 0X4_D_2_C_6_D_F_C, 0X5_3_3_8_0_D_1_3, 0X6_5_0_A_7_3_5_4, 0X7_6_6_A_0_A_B_B, 0X8_1_C_2_C_9_2_E, 0X9_2_7_2_2_C_8_5, 0XA_2_B_F_E_8_A_1, 0XA_8_1_A_6_6_4_B, 0XC_2_4_B_8_B_7_0, 0XC_7_6_C_5_1_A_3, 0XD_1_9_2_E_8_1_9, 0XD_6_9_9_0_6_2_4, 0XF_4_0_E_3_5_8_5, 0X1_0_6_A_A_0_7_0, 0X1_9_A_4_C_1_1_6, 0X1_E_3_7_6_C_0_8, 0X2_7_4_8_7_7_4_C, 0X3_4_B_0_B_C_B_5, 0X3_9_1_C_0_C_B_3, 0X4_E_D_8_A_A_4_A, 0X5_B_9_C_C_A_4_F, 0X6_8_2_E_6_F_F_3, 0X7_4_8_F_8_2_E_E, 0X7_8_A_5_6_3_6_F, 0X8_4_C_8_7_8_1_4, 0X8_C_C_7_0_2_0_8, 0X9_0_B_E_F_F_F_A, 0XA_4_5_0_6_C_E_B, 0XB_E_F_9_A_3_F_7, 0XC_6_7_1_7_8_F_2, ] A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : bytes ) -> bytes: A = B'\x80' + (B'\x00' * (63 - (len(A_ ) + 8) % 64)) A = struct.pack('>Q' ,(len(A_ ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: # Convert into blocks of 64 bytes A = [ self.preprocessed_data[x : x + 64] for x in range(0 ,len(self.preprocessed_data ) ,64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers A = list(struct.unpack('>16L' ,A_ ) ) # add 48 0-ed integers words += [0] * 48 A , A , A , A , A , A , A , A = self.hashes for index in range(0 ,64 ): if index > 15: # modify the zero-ed indexes at the end of the array A = ( self.ror(words[index - 15] ,7 ) ^ self.ror(words[index - 15] ,18 ) ^ (words[index - 15] >> 3) ) A = ( self.ror(words[index - 2] ,17 ) ^ self.ror(words[index - 2] ,19 ) ^ (words[index - 2] >> 10) ) A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0_0_0_0_0_0_0_0 # Compression A = self.ror(A_ ,6 ) ^ self.ror(A_ ,11 ) ^ self.ror(A_ ,25 ) A = (e & f) ^ ((~e & 0XF_F_F_F_F_F_F_F) & g) A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0_0_0_0_0_0_0_0 A = self.ror(A_ ,2 ) ^ self.ror(A_ ,13 ) ^ self.ror(A_ ,22 ) A = (a & b) ^ (a & c) ^ (b & c) A = (sa + maj) % 0X1_0_0_0_0_0_0_0_0 A , A , A , A , A , A , A , A = ( g, f, e, ((d + tempa) % 0X1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0X1_0_0_0_0_0_0_0_0), ) A = [a, b, c, d, e, f, g, h] # Modify final values A = [ ((element + mutated_hash_values[index]) % 0X1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] A = ''.join([hex(A_ )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : int ) -> int: return 0XF_F_F_F_F_F_F_F & (value << (32 - rotations)) | (value >> rotations) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> None: import hashlib A = bytes('Test String' ,'utf-8' ) self.assertEqual(SHAaaa(A_ ).hash ,hashlib.shaaaa(A_ ).hexdigest() ) def _snake_case ( ): import doctest doctest.testmod() A = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) A = parser.parse_args() A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: A = f.read() else: A = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
74
0
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self : Dict ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = get_activation('swish' ) self.assertIsInstance(lowerCamelCase__ ,nn.SiLU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' _UpperCamelCase : List[str] = get_activation('silu' ) self.assertIsInstance(lowerCamelCase__ ,nn.SiLU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' _UpperCamelCase : Dict = get_activation('mish' ) self.assertIsInstance(lowerCamelCase__ ,nn.Mish ) self.assertEqual(act(torch.tensor(-200 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def UpperCamelCase_ ( self : int ): '''simple docstring''' _UpperCamelCase : Dict = get_activation('gelu' ) self.assertIsInstance(lowerCamelCase__ ,nn.GELU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 )
83
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''DeiTFeatureExtractor'''] _lowercase = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDeiTForImageClassification''', '''TFDeiTForImageClassificationWithTeacher''', '''TFDeiTForMaskedImageModeling''', '''TFDeiTModel''', '''TFDeiTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
0
"""simple docstring""" from __future__ import annotations def _snake_case ( lowercase__ : str , lowercase__ : list[str] | None = None ) -> list[list[str]]: '''simple docstring''' lowerCAmelCase_ :List[Any] = word_bank or [] # create a table lowerCAmelCase_ :int = len(lowercase__ ) + 1 lowerCAmelCase_ :list[list[list[str]]] = [] for _ in range(lowercase__ ): table.append([] ) # seed value lowerCAmelCase_ :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: lowerCAmelCase_ :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'], ) )
84
"""simple docstring""" from __future__ import annotations import requests def _snake_case ( snake_case__ : str ): A = F'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case__ ).json() def _snake_case ( snake_case__ : int = 10 ): A = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' A = requests.get(snake_case__ ).json()[:max_stories] return [get_hackernews_story(snake_case__ ) for story_id in story_ids] def _snake_case ( snake_case__ : int = 10 ): A = hackernews_top_stories(snake_case__ ) return "\n".join('* [{title}]({url})'.format(**snake_case__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
74
0
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = IFInpaintingPipeline lowerCAmelCase_ : Tuple = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} lowerCAmelCase_ : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase_ : Optional[int] = PipelineTesterMixin.required_optional_params - {"latents"} def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' return self._get_dummy_components() def lowerCAmelCase__ ( self , a__ , a__=0 ) -> Dict: '''simple docstring''' if str(a__ ).startswith("mps" ): snake_case_ = torch.manual_seed(a__ ) else: snake_case_ = torch.Generator(device=a__ ).manual_seed(a__ ) snake_case_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) snake_case_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) snake_case_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self._test_save_load_local() def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
85
"""simple docstring""" from string import ascii_uppercase _lowercase = {char: i for i, char in enumerate(ascii_uppercase)} _lowercase = dict(enumerate(ascii_uppercase)) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = len(snake_case__ ) A = 0 while True: if x == i: A = 0 if len(snake_case__ ) == len(snake_case__ ): break key += key[i] i += 1 return key def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in message: if letter == " ": cipher_text += " " else: A = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: A = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _snake_case ( ): A = 'THE GERMAN ATTACK' A = 'SECRET' A = generate_key(snake_case__ , snake_case__ ) A = cipher_text(snake_case__ , snake_case__ ) print(F'Encrypted Text = {s}' ) print(F'Original Text = {original_text(snake_case__ , snake_case__ )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
74
0
"""simple docstring""" import functools from typing import Any def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): # Validation if not isinstance(_UpperCamelCase , _UpperCamelCase ) or len(_UpperCamelCase ) == 0: raise ValueError('the string should be not empty string' ) if not isinstance(_UpperCamelCase , _UpperCamelCase ) or not all( isinstance(_UpperCamelCase , _UpperCamelCase ) and len(_UpperCamelCase ) > 0 for item in words ): raise ValueError('the words should be a list of non-empty strings' ) # Build trie __lowerCAmelCase : dict[str, Any] = {} __lowerCAmelCase : Optional[Any] = 'WORD_KEEPER' for word in words: __lowerCAmelCase : Optional[int] = trie for c in word: if c not in trie_node: __lowerCAmelCase : Optional[int] = {} __lowerCAmelCase : Any = trie_node[c] __lowerCAmelCase : Any = True __lowerCAmelCase : List[str] = len(_UpperCamelCase ) # Dynamic programming method @functools.cache def is_breakable(_UpperCamelCase ) -> bool: if index == len_string: return True __lowerCAmelCase : Union[str, Any] = trie for i in range(_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : str = trie_node.get(string[i] , _UpperCamelCase ) if trie_node is None: return False if trie_node.get(_UpperCamelCase , _UpperCamelCase ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
86
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ) -> Optional[Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] ,model_result['ss'] ): A = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = 'sgugger/tiny-distilbert-classification' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,only_pretrain_model=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,torchscript=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,fpaa=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) # set architectures equal to `None` A = None A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' ,'Can\'t do half precision' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,fpaa=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,save_to_csv=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,inference_time_csv_file=os.path.join(A_ ,'inf_time.csv' ) ,train_memory_csv_file=os.path.join(A_ ,'train_mem.csv' ) ,inference_memory_csv_file=os.path.join(A_ ,'inf_mem.csv' ) ,train_time_csv_file=os.path.join(A_ ,'train_time.csv' ) ,env_info_csv_file=os.path.join(A_ ,'env.csv' ) ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) benchmark.run() self.assertTrue(Path(os.path.join(A_ ,'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'env.csv' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(A_ : Optional[int] ): self.assertTrue(hasattr(A_ ,'sequential' ) ) self.assertTrue(hasattr(A_ ,'cumulative' ) ) self.assertTrue(hasattr(A_ ,'current' ) ) self.assertTrue(hasattr(A_ ,'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,log_filename=os.path.join(A_ ,'log.txt' ) ,log_print=A_ ,trace_memory_line_by_line=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A_ ,'log.txt' ) ).exists() )
74
0
import glob import os import random from string import ascii_lowercase, digits import cva UpperCamelCase = '''''' UpperCamelCase = '''''' UpperCamelCase = '''''' UpperCamelCase = 1 # (0 is vertical, 1 is horizontal) def lowercase_ ( ): lowercase__ , lowercase__ : Optional[Any] = get_dataset(_lowerCamelCase , _lowerCamelCase) print("Processing...") lowercase__ , lowercase__ , lowercase__ : List[str] = update_image_and_anno(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) for index, image in enumerate(_lowerCamelCase): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowercase__ : Optional[Any] = random_chars(32) lowercase__ : Dict = paths[index].split(os.sep)[-1].rsplit("." , 1)[0] lowercase__ : Optional[Any] = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' , _lowerCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85]) print(f'''Success {index+1}/{len(_lowerCamelCase)} with {file_name}''') lowercase__ : Any = [] for anno in new_annos[index]: lowercase__ : Any = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(_lowerCamelCase) with open(f'''/{file_root}.txt''' , "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def lowercase_ ( _lowerCamelCase : str , _lowerCamelCase : str): lowercase__ : List[Any] = [] lowercase__ : Optional[int] = [] for label_file in glob.glob(os.path.join(_lowerCamelCase , "*.txt")): lowercase__ : Optional[int] = label_file.split(os.sep)[-1].rsplit("." , 1)[0] with open(_lowerCamelCase) as in_file: lowercase__ : Optional[Any] = in_file.readlines() lowercase__ : str = os.path.join(_lowerCamelCase , f'''{label_name}.jpg''') lowercase__ : Dict = [] for obj_list in obj_lists: lowercase__ : List[str] = obj_list.rstrip("\n").split(" ") boxes.append( [ int(obj[0]), float(obj[1]), float(obj[2]), float(obj[3]), float(obj[4]), ]) if not boxes: continue img_paths.append(_lowerCamelCase) labels.append(_lowerCamelCase) return img_paths, labels def lowercase_ ( _lowerCamelCase : list , _lowerCamelCase : list , _lowerCamelCase : int = 1): lowercase__ : Union[str, Any] = [] lowercase__ : Any = [] lowercase__ : Optional[Any] = [] for idx in range(len(_lowerCamelCase)): lowercase__ : Tuple = [] lowercase__ : Dict = img_list[idx] path_list.append(_lowerCamelCase) lowercase__ : Optional[int] = anno_list[idx] lowercase__ : Optional[Any] = cva.imread(_lowerCamelCase) if flip_type == 1: lowercase__ : List[str] = cva.flip(_lowerCamelCase , _lowerCamelCase) for bbox in img_annos: lowercase__ : List[Any] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]]) elif flip_type == 0: lowercase__ : Any = cva.flip(_lowerCamelCase , _lowerCamelCase) for bbox in img_annos: lowercase__ : Dict = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]]) new_annos_lists.append(_lowerCamelCase) new_imgs_list.append(_lowerCamelCase) return new_imgs_list, new_annos_lists, path_list def lowercase_ ( _lowerCamelCase : int = 32): assert number_char > 1, "The number of character should greater than 1" lowercase__ : List[Any] = ascii_lowercase + digits return "".join(random.choice(_lowerCamelCase) for _ in range(_lowerCamelCase)) if __name__ == "__main__": main() print('''DONE ✅''')
87
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _lowercase = re.compile(r'''^(?P<major>\d+)''' r'''\.(?P<minor>\d+)''' r'''\.(?P<patch>\d+)$''') @total_ordering @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: A , A , A = _str_to_version_tuple(self.version_str ) def __repr__( self : Optional[int] ) -> Dict: return F'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return self.major, self.minor, self.patch def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Tuple ) -> Union[str, Any]: if isinstance(A_ ,A_ ): return Version(A_ ) elif isinstance(A_ ,A_ ): return other raise TypeError(F'{other} (type {type(A_ )}) cannot be compared to version.' ) def __eq__( self : List[Any] ,A_ : Dict ) -> Any: try: A = self._validate_operand(A_ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : List[Any] ,A_ : Optional[int] ) -> Tuple: A = self._validate_operand(A_ ) return self.tuple < other.tuple def __hash__( self : Union[str, Any] ) -> Union[str, Any]: return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[str] ) -> List[str]: A = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.version_str def _snake_case ( snake_case__ : List[str] ): A = _VERSION_REG.match(snake_case__ ) if not res: raise ValueError(F'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(snake_case__ ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def _snake_case ( snake_case__ : str ): return ".".join(str(snake_case__ ) for v in version_tuple )
74
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self : List[Any] ) -> List[Any]: """simple docstring""" __magic_name__ = tempfile.mkdtemp() __magic_name__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __magic_name__ = 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] ) ) __magic_name__ = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __magic_name__ = os.path.join(self.tmpdirname , UpperCamelCase__ ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(UpperCamelCase__ , UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] , **UpperCamelCase__ : Tuple ) -> Dict: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : str , **UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , **UpperCamelCase__ : Tuple ) -> Optional[Any]: """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _lowercase ( self : str ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _lowercase ( self : Optional[Any] ) -> str: """simple docstring""" __magic_name__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __magic_name__ = [Image.fromarray(np.moveaxis(UpperCamelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self : int ) -> int: """simple docstring""" __magic_name__ = self.get_tokenizer() __magic_name__ = self.get_rust_tokenizer() __magic_name__ = self.get_image_processor() __magic_name__ = AlignProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) __magic_name__ = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCamelCase__ ) __magic_name__ = AlignProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) __magic_name__ = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , UpperCamelCase__ ) self.assertIsInstance(processor_fast.tokenizer , UpperCamelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , UpperCamelCase__ ) self.assertIsInstance(processor_fast.image_processor , UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __magic_name__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __magic_name__ = self.get_image_processor(do_normalize=UpperCamelCase__ , padding_value=1.0 ) __magic_name__ = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=UpperCamelCase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCamelCase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> Tuple: """simple docstring""" __magic_name__ = self.get_image_processor() __magic_name__ = self.get_tokenizer() __magic_name__ = AlignProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ ) __magic_name__ = self.prepare_image_inputs() __magic_name__ = image_processor(UpperCamelCase__ , return_tensors="""np""" ) __magic_name__ = processor(images=UpperCamelCase__ , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _lowercase ( self : List[Any] ) -> str: """simple docstring""" __magic_name__ = self.get_image_processor() __magic_name__ = self.get_tokenizer() __magic_name__ = AlignProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ ) __magic_name__ = """lower newer""" __magic_name__ = processor(text=UpperCamelCase__ ) __magic_name__ = tokenizer(UpperCamelCase__ , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self : List[str] ) -> int: """simple docstring""" __magic_name__ = self.get_image_processor() __magic_name__ = self.get_tokenizer() __magic_name__ = AlignProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ ) __magic_name__ = """lower newer""" __magic_name__ = self.prepare_image_inputs() __magic_name__ = processor(text=UpperCamelCase__ , images=UpperCamelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(UpperCamelCase__ ): processor() def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = self.get_image_processor() __magic_name__ = self.get_tokenizer() __magic_name__ = AlignProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ ) __magic_name__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __magic_name__ = processor.batch_decode(UpperCamelCase__ ) __magic_name__ = tokenizer.batch_decode(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[str]: """simple docstring""" __magic_name__ = self.get_image_processor() __magic_name__ = self.get_tokenizer() __magic_name__ = AlignProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ ) __magic_name__ = """lower newer""" __magic_name__ = self.prepare_image_inputs() __magic_name__ = processor(text=UpperCamelCase__ , images=UpperCamelCase__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
88
"""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 _lowercase = NewType('''DataClass''', Any) _lowercase = NewType('''DataClassType''', Any) def _snake_case ( snake_case__ : Tuple ): if isinstance(snake_case__ , snake_case__ ): 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 _snake_case ( snake_case__ : list ): A = {str(snake_case__ ): choice for choice in choices} return lambda snake_case__ : str_to_choice.get(snake_case__ , snake_case__ ) def _snake_case ( *, snake_case__ : Union[str, List[str]] = None , snake_case__ : str = None , snake_case__ : Any = dataclasses.MISSING , snake_case__ : Callable[[], Any] = dataclasses.MISSING , snake_case__ : dict = None , **snake_case__ : Any , ): if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls A = {} if aliases is not None: A = aliases if help is not None: A = help return dataclasses.field(metadata=snake_case__ , default=snake_case__ , default_factory=snake_case__ , **snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Iterable[DataClassType] def __init__( self : List[str] ,A_ : Union[DataClassType, Iterable[DataClassType]] ,**A_ : Any ) -> Optional[int]: # To make the default appear when using --help if "formatter_class" not in kwargs: A = ArgumentDefaultsHelpFormatter super().__init__(**A_ ) if dataclasses.is_dataclass(A_ ): A = [dataclass_types] A = list(A_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ,A_ : dataclasses.Field ) -> Optional[Any]: A = F'--{field.name}' A = 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 ,A_ ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) A = kwargs.pop('aliases' ,[] ) if isinstance(A_ ,A_ ): A = [aliases] A = getattr(field.type ,'__origin__' ,field.type ) if origin_type is Union or (hasattr(A_ ,'UnionType' ) and isinstance(A_ ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A_ ) 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(A_ ) not in field.type.__args__: # filter `str` in Union A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] A = getattr(field.type ,'__origin__' ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) A = ( field.type.__args__[0] if isinstance(A_ ,field.type.__args__[1] ) else field.type.__args__[1] ) A = 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) A = {} if origin_type is Literal or (isinstance(field.type ,A_ ) and issubclass(field.type ,A_ )): if origin_type is Literal: A = field.type.__args__ else: A = [x.value for x in field.type] A = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: A = field.default else: A = 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 A = copy(A_ ) # Hack because type=bool in argparse does not behave as we want. A = 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. A = 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 A = default # This tells argparse we accept 0 or 1 value after --field_name A = '?' # This is the value that will get picked if we do --field_name (without value) A = True elif isclass(A_ ) and issubclass(A_ ,A_ ): A = field.type.__args__[0] A = '+' if field.default_factory is not dataclasses.MISSING: A = field.default_factory() elif field.default is dataclasses.MISSING: A = True else: A = field.type if field.default is not dataclasses.MISSING: A = field.default elif field.default_factory is not dataclasses.MISSING: A = field.default_factory() else: A = True parser.add_argument(A_ ,*A_ ,**A_ ) # 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]): A = False parser.add_argument(F'--no_{field.name}' ,action='store_false' ,dest=field.name ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : DataClassType ) -> List[Any]: if hasattr(A_ ,'_argument_group_name' ): A = self.add_argument_group(dtype._argument_group_name ) else: A = self try: A = get_type_hints(A_ ) 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(A_ ): A = '.'.join(map(A_ ,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(A_ ): if not field.init: continue A = type_hints[field.name] self._parse_dataclass_field(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Any=None ,A_ : int=False ,A_ : Any=True ,A_ : List[str]=None ,A_ : Union[str, Any]=None ,) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): A = [] if args_filename: args_files.append(Path(A_ ) ) 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 A = ArgumentParser() args_file_parser.add_argument(A_ ,type=A_ ,action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) A , A = args_file_parser.parse_known_args(args=A_ ) A = vars(A_ ).get(args_file_flag.lstrip('-' ) ,A_ ) if cmd_args_file_paths: args_files.extend([Path(A_ ) for p in cmd_args_file_paths] ) A = [] 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 A = file_args + args if args is not None else file_args + sys.argv[1:] A , A = self.parse_known_args(args=A_ ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in vars(A_ ).items() if k in keys} for k in keys: delattr(A_ ,A_ ) A = dtype(**A_ ) outputs.append(A_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A_ ) 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 _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Dict[str, Any] ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = set(args.keys() ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) A = dtype(**A_ ) outputs.append(A_ ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(A_ )}' ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: with open(Path(A_ ) ,encoding='utf-8' ) as open_json_file: A = json.loads(open_json_file.read() ) A = self.parse_dict(A_ ,allow_extra_keys=A_ ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = self.parse_dict(yaml.safe_load(Path(A_ ).read_text() ) ,allow_extra_keys=A_ ) return tuple(A_ )
74
0
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os 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 __lowerCAmelCase = '''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 __lowerCamelCase ( ) -> Optional[int]: _a : List[Any] = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: _a : Any = get_sagemaker_input() else: _a : Optional[Any] = get_cluster_input() return config def __lowerCamelCase ( lowerCAmelCase_=None ) -> Any: if subparsers is not None: _a : Tuple = subparsers.add_parser('config' , description=lowerCAmelCase_ ) else: _a : List[Any] = argparse.ArgumentParser('Accelerate config command' , description=lowerCAmelCase_ ) parser.add_argument( '--config_file' , default=lowerCAmelCase_ , 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=lowerCAmelCase_ ) return parser def __lowerCamelCase ( lowerCAmelCase_ ) -> Union[str, Any]: _a : Dict = get_user_input() if args.config_file is not None: _a : List[Any] = args.config_file else: if not os.path.isdir(lowerCAmelCase_ ): os.makedirs(lowerCAmelCase_ ) _a : str = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowerCAmelCase_ ) else: config.to_yaml_file(lowerCAmelCase_ ) print(f"""accelerate configuration saved at {config_file}""" ) def __lowerCamelCase ( ) -> Any: _a : Union[str, Any] = config_command_parser() _a : List[Any] = parser.parse_args() config_command(lowerCAmelCase_ ) if __name__ == "__main__": main()
89
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Dict ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : int ): # 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(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Optional[int] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
74
0
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __A = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" snake_case_ = ['''input_features''', '''is_longer'''] def __init__( self , lowerCamelCase__=64 , lowerCamelCase__=48_000 , lowerCamelCase__=480 , lowerCamelCase__=10 , lowerCamelCase__=1_024 , lowerCamelCase__=0.0 , lowerCamelCase__=False , lowerCamelCase__ = 0 , lowerCamelCase__ = 14_000 , lowerCamelCase__ = None , lowerCamelCase__ = "fusion" , lowerCamelCase__ = "repeatpad" , **lowerCamelCase__ , ) -> Tuple: '''simple docstring''' super().__init__( feature_size=lowerCamelCase__ , sampling_rate=lowerCamelCase__ , padding_value=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , **lowerCamelCase__ , ) __lowerCamelCase = top_db __lowerCamelCase = truncation __lowerCamelCase = padding __lowerCamelCase = fft_window_size __lowerCamelCase = (fft_window_size >> 1) + 1 __lowerCamelCase = hop_length __lowerCamelCase = max_length_s __lowerCamelCase = max_length_s * sampling_rate __lowerCamelCase = sampling_rate __lowerCamelCase = frequency_min __lowerCamelCase = frequency_max __lowerCamelCase = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=lowerCamelCase__ , min_frequency=lowerCamelCase__ , max_frequency=lowerCamelCase__ , sampling_rate=lowerCamelCase__ , norm=lowerCamelCase__ , mel_scale='htk' , ) __lowerCamelCase = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=lowerCamelCase__ , min_frequency=lowerCamelCase__ , max_frequency=lowerCamelCase__ , sampling_rate=lowerCamelCase__ , norm='slaney' , mel_scale='slaney' , ) def lowercase_ ( self ) -> Dict[str, Any]: '''simple docstring''' __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> np.ndarray: '''simple docstring''' __lowerCamelCase = spectrogram( lowerCamelCase__ , window_function(self.fft_window_size , 'hann' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=lowerCamelCase__ , log_mel='dB' , ) return log_mel_spectrogram.T def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> int: '''simple docstring''' __lowerCamelCase = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk __lowerCamelCase = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk __lowerCamelCase = [0] # randomly choose index for each part __lowerCamelCase = np.random.choice(ranges[0] ) __lowerCamelCase = np.random.choice(ranges[1] ) __lowerCamelCase = np.random.choice(ranges[2] ) __lowerCamelCase = mel[idx_front : idx_front + chunk_frames, :] __lowerCamelCase = mel[idx_middle : idx_middle + chunk_frames, :] __lowerCamelCase = mel[idx_back : idx_back + chunk_frames, :] __lowerCamelCase = torch.tensor(mel[None, None, :] ) __lowerCamelCase = torch.nn.functional.interpolate( lowerCamelCase__ , size=[chunk_frames, 64] , mode='bilinear' , align_corners=lowerCamelCase__ ) __lowerCamelCase = mel_shrink[0][0].numpy() __lowerCamelCase = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.array: '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": __lowerCamelCase = True # random crop to max_length (for compatibility) -> this should be handled by self.pad __lowerCamelCase = len(lowerCamelCase__ ) - max_length __lowerCamelCase = np.random.randint(0 , overflow + 1 ) __lowerCamelCase = waveform[idx : idx + max_length] __lowerCamelCase = self._np_extract_fbank_features(lowerCamelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": __lowerCamelCase = self._np_extract_fbank_features(lowerCamelCase__ , self.mel_filters ) __lowerCamelCase = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed __lowerCamelCase = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. __lowerCamelCase = np.stack([mel, mel, mel, mel] , axis=0 ) __lowerCamelCase = False else: __lowerCamelCase = self._random_mel_fusion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase = True else: raise NotImplementedError(f"""data_truncating {truncation} not implemented""" ) else: __lowerCamelCase = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": __lowerCamelCase = int(max_length / len(lowerCamelCase__ ) ) __lowerCamelCase = np.stack(np.tile(lowerCamelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": __lowerCamelCase = int(max_length / len(lowerCamelCase__ ) ) __lowerCamelCase = np.stack(np.tile(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase = np.pad(lowerCamelCase__ , (0, max_length - waveform.shape[0]) , mode='constant' , constant_values=0 ) if truncation == "fusion": __lowerCamelCase = self._np_extract_fbank_features(lowerCamelCase__ , self.mel_filters ) __lowerCamelCase = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: __lowerCamelCase = self._np_extract_fbank_features(lowerCamelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> BatchFeature: '''simple docstring''' __lowerCamelCase = truncation if truncation is not None else self.truncation __lowerCamelCase = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" f""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) __lowerCamelCase = isinstance(lowerCamelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) __lowerCamelCase = is_batched_numpy or ( isinstance(lowerCamelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __lowerCamelCase = [np.asarray(lowerCamelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(lowerCamelCase__ , np.ndarray ): __lowerCamelCase = np.asarray(lowerCamelCase__ , dtype=np.floataa ) elif isinstance(lowerCamelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __lowerCamelCase = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __lowerCamelCase = [np.asarray(lowerCamelCase__ )] # convert to mel spectrogram, truncate and pad if needed. __lowerCamelCase = [ self._get_input_mel(lowerCamelCase__ , max_length if max_length else self.nb_max_samples , lowerCamelCase__ , lowerCamelCase__ ) for waveform in raw_speech ] __lowerCamelCase = [] __lowerCamelCase = [] for mel, longer in padded_inputs: input_mel.append(lowerCamelCase__ ) is_longer.append(lowerCamelCase__ ) if truncation == "fusion" and sum(lowerCamelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer __lowerCamelCase = np.random.randint(0 , len(lowerCamelCase__ ) ) __lowerCamelCase = True if isinstance(input_mel[0] , lowerCamelCase__ ): __lowerCamelCase = [np.asarray(lowerCamelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool __lowerCamelCase = [[longer] for longer in is_longer] __lowerCamelCase = {'input_features': input_mel, 'is_longer': is_longer} __lowerCamelCase = BatchFeature(lowerCamelCase__ ) if return_tensors is not None: __lowerCamelCase = input_features.convert_to_tensors(lowerCamelCase__ ) return input_features
90
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
0
"""simple docstring""" import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 UpperCAmelCase_ : List[str] = get_tests_dir("""fixtures/dummy_feature_extractor_config.json""") UpperCAmelCase_ : Optional[Any] = get_tests_dir("""fixtures/vocab.json""") UpperCAmelCase_ : List[Any] = get_tests_dir("""fixtures""") class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = 0 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h''') self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : str = WavaVecaConfig() SCREAMING_SNAKE_CASE_ : List[str] = AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h''') # save in new folder model_config.save_pretrained(lowercase_) processor.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , lowercase_)) copyfile(lowercase_ , os.path.join(lowercase_ , '''vocab.json''')) SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : str = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE_ : List[Any] = AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h''') SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaProcessor(lowercase_ , lowercase_) # save in new folder processor.save_pretrained(lowercase_) # drop `processor_class` in tokenizer with open(os.path.join(lowercase_ , lowercase_) , '''r''') as f: SCREAMING_SNAKE_CASE_ : List[Any] = json.load(lowercase_) config_dict.pop('''processor_class''') with open(os.path.join(lowercase_ , lowercase_) , '''w''') as f: f.write(json.dumps(lowercase_)) SCREAMING_SNAKE_CASE_ : List[Any] = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : str = WavaVecaFeatureExtractor() SCREAMING_SNAKE_CASE_ : int = AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h''') SCREAMING_SNAKE_CASE_ : str = WavaVecaProcessor(lowercase_ , lowercase_) # save in new folder processor.save_pretrained(lowercase_) # drop `processor_class` in feature extractor with open(os.path.join(lowercase_ , lowercase_) , '''r''') as f: SCREAMING_SNAKE_CASE_ : Dict = json.load(lowercase_) config_dict.pop('''processor_class''') with open(os.path.join(lowercase_ , lowercase_) , '''w''') as f: f.write(json.dumps(lowercase_)) SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaConfig(processor_class='''Wav2Vec2Processor''') model_config.save_pretrained(lowercase_) # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , '''vocab.json''')) # create emtpy sample processor with open(os.path.join(lowercase_ , lowercase_) , '''w''') as f: f.write('''{}''') SCREAMING_SNAKE_CASE_ : int = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : str = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''') # If remote code is disabled, we can't load this config. with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) self.assertTrue(processor.special_attribute_present) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') SCREAMING_SNAKE_CASE_ : Tuple = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present) self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''') # Test we can also load the slow version SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_ , use_fast=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present) self.assertEqual(new_tokenizer.__class__.__name__ , '''NewTokenizer''') else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''') def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' try: AutoConfig.register('''custom''' , lowercase_) AutoFeatureExtractor.register(lowercase_ , lowercase_) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_) AutoProcessor.register(lowercase_ , lowercase_) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowercase_): AutoProcessor.register(lowercase_ , lowercase_) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE_ : Union[str, Any] = CustomFeatureExtractor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : List[str] = CustomTokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = CustomProcessor(lowercase_ , lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : str = AutoProcessor.from_pretrained(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = False class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = False class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "AutoFeatureExtractor" __UpperCamelCase = "AutoTokenizer" __UpperCamelCase = False try: AutoConfig.register('''custom''' , lowercase_) AutoFeatureExtractor.register(lowercase_ , lowercase_) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_) AutoProcessor.register(lowercase_ , lowercase_) # If remote code is not set, the default is to use local classes. SCREAMING_SNAKE_CASE_ : int = AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor''') self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') self.assertFalse(processor.special_attribute_present) self.assertFalse(processor.feature_extractor.special_attribute_present) self.assertFalse(processor.tokenizer.special_attribute_present) # If remote code is disabled, we load the local ones. SCREAMING_SNAKE_CASE_ : Any = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') self.assertFalse(processor.special_attribute_present) self.assertFalse(processor.feature_extractor.special_attribute_present) self.assertFalse(processor.tokenizer.special_attribute_present) # If remote is enabled, we load from the Hub. SCREAMING_SNAKE_CASE_ : Optional[int] = AutoProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_processor''' , trust_remote_code=lowercase_) self.assertEqual(processor.__class__.__name__ , '''NewProcessor''') self.assertTrue(processor.special_attribute_present) self.assertTrue(processor.feature_extractor.special_attribute_present) self.assertTrue(processor.tokenizer.special_attribute_present) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert''') self.assertEqual(processor.__class__.__name__ , '''BertTokenizerFast''') def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext''') self.assertEqual(processor.__class__.__name__ , '''ConvNextImageProcessor''') @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-processor''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-processor-org''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-processor''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaProcessor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , '''test-processor''') , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : List[str] = WavaVecaProcessor.from_pretrained(F'{USER}/test-processor') for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_)) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab()) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = WavaVecaProcessor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , '''test-processor-org''') , push_to_hub=lowercase_ , use_auth_token=self._token , organization='''valid_org''' , ) SCREAMING_SNAKE_CASE_ : str = WavaVecaProcessor.from_pretrained('''valid_org/test-processor-org''') for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_)) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab()) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() SCREAMING_SNAKE_CASE_ : Optional[int] = CustomFeatureExtractor.from_pretrained(lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ : Any = os.path.join(lowercase_ , '''vocab.txt''') with open(lowercase_ , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE_ : List[str] = CustomTokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = CustomProcessor(lowercase_ , lowercase_) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(F'{USER}/test-dynamic-processor' , token=self._token) SCREAMING_SNAKE_CASE_ : Union[str, Any] = Repository(lowercase_ , clone_from=F'{USER}/test-dynamic-processor' , token=self._token) processor.save_pretrained(lowercase_) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { '''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor''', '''AutoProcessor''': '''custom_processing.CustomProcessor''', } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(lowercase_ , '''tokenizer_config.json''')) as f: SCREAMING_SNAKE_CASE_ : Dict = json.load(lowercase_) self.assertDictEqual( tokenizer_config['''auto_map'''] , { '''AutoTokenizer''': ['''custom_tokenization.CustomTokenizer''', None], '''AutoProcessor''': '''custom_processing.CustomProcessor''', } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(lowercase_ , '''custom_feature_extraction.py'''))) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , '''custom_tokenization.py'''))) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , '''custom_processing.py'''))) repo.push_to_hub() SCREAMING_SNAKE_CASE_ : Tuple = AutoProcessor.from_pretrained(F'{USER}/test-dynamic-processor' , trust_remote_code=lowercase_) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , '''CustomProcessor''')
91
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase = logging.get_logger(__name__) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : int ,**A_ : Any ) -> Any: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A = deprecated_arg[3:] A = not kwargs.pop(A_ ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) A = kwargs.pop('tpu_name' ,self.tpu_name ) A = kwargs.pop('device_idx' ,self.device_idx ) A = kwargs.pop('eager_mode' ,self.eager_mode ) A = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**A_ ) _lowerCamelCase: str = field( default=_lowercase , metadata={'''help''': '''Name of TPU'''} , ) _lowerCamelCase: int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) _lowerCamelCase: bool = field(default=_lowercase , metadata={'''help''': '''Benchmark models in eager model.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) A = None if self.tpu: try: if self.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: A = None return tpu @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) A = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) A = tf.distribute.OneDeviceStrategy(device=F'/gpu:{self.device_idx}' ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU A = tf.distribute.OneDeviceStrategy(device=F'/cpu:{self.device_idx}' ) return strategy @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def _SCREAMING_SNAKE_CASE ( self : int ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _SCREAMING_SNAKE_CASE ( self : str ) -> bool: return self.n_gpu > 0
74
0
def _a ( SCREAMING_SNAKE_CASE_ : str = "The quick brown fox jumps over the lazy dog" , ): __lowerCAmelCase = set() # Replace all the whitespace in our sentence __lowerCAmelCase = input_str.replace(" " , "" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(SCREAMING_SNAKE_CASE_ ) == 26 def _a ( SCREAMING_SNAKE_CASE_ : str = "The quick brown fox jumps over the lazy dog" , ): __lowerCAmelCase = [False] * 26 for char in input_str: if char.islower(): __lowerCAmelCase = True elif char.isupper(): __lowerCAmelCase = True return all(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : str = "The quick brown fox jumps over the lazy dog" , ): return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _a ( ): from timeit import timeit __lowerCAmelCase = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=SCREAMING_SNAKE_CASE_ ) ) print(timeit("is_pangram_faster()" , setup=SCREAMING_SNAKE_CASE_ ) ) print(timeit("is_pangram_fastest()" , setup=SCREAMING_SNAKE_CASE_ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
92
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowercase = logging.get_logger(__name__) _lowercase = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''dpt''' def __init__( self : str ,A_ : Tuple=768 ,A_ : int=12 ,A_ : Optional[int]=12 ,A_ : Optional[int]=3072 ,A_ : List[str]="gelu" ,A_ : str=0.0 ,A_ : int=0.0 ,A_ : str=0.02 ,A_ : str=1e-12 ,A_ : str=384 ,A_ : Dict=16 ,A_ : Union[str, Any]=3 ,A_ : Dict=False ,A_ : Any=True ,A_ : Optional[int]=[2, 5, 8, 11] ,A_ : Optional[Any]="project" ,A_ : Tuple=[4, 2, 1, 0.5] ,A_ : int=[96, 192, 384, 768] ,A_ : int=256 ,A_ : str=-1 ,A_ : Optional[int]=False ,A_ : Optional[int]=True ,A_ : Union[str, Any]=0.4 ,A_ : Union[str, Any]=255 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=[1, 1024, 24, 24] ,A_ : List[str]=[0, 1] ,A_ : List[Any]=None ,**A_ : Tuple ,) -> Union[str, Any]: super().__init__(**A_ ) A = hidden_size A = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): logger.info('Initializing the config with a `BiT` backbone.' ) A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): A = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) A = backbone_featmap_shape A = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: A = None A = None A = [] A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) A = readout_type A = reassemble_factors A = neck_hidden_sizes A = fusion_hidden_size A = head_in_index A = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) A = use_auxiliary_head A = auxiliary_loss_weight A = semantic_loss_ignore_index A = semantic_classifier_dropout def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: A = self.backbone_config.to_dict() A = self.__class__.model_type return output
74
0
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
0
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging snake_case : Any = logging.get_logger(__name__) class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = ['input_values', 'attention_mask'] def __init__( self , _lowerCamelCase = 1 , _lowerCamelCase = 1_6000 , _lowerCamelCase = 0.0 , _lowerCamelCase = False , _lowerCamelCase = 80 , _lowerCamelCase = 16 , _lowerCamelCase = 64 , _lowerCamelCase = "hann_window" , _lowerCamelCase = 1.0 , _lowerCamelCase = 80 , _lowerCamelCase = 7600 , _lowerCamelCase = 1e-10 , _lowerCamelCase = 2 , _lowerCamelCase = True , **_lowerCamelCase , ): super().__init__(feature_size=_lowerCamelCase , sampling_rate=_lowerCamelCase , padding_value=_lowerCamelCase , **_lowerCamelCase ) a :Union[str, Any] = do_normalize a :List[Any] = return_attention_mask a :List[str] = num_mel_bins a :List[str] = hop_length a :List[Any] = win_length a :List[Any] = win_function a :List[str] = frame_signal_scale a :List[str] = fmin a :Tuple = fmax a :List[Any] = mel_floor a :Union[str, Any] = reduction_factor a :Union[str, Any] = win_length * sampling_rate // 1000 a :Dict = hop_length * sampling_rate // 1000 a :Any = optimal_fft_length(self.sample_size ) a :List[Any] = (self.n_fft // 2) + 1 a :Any = window_function(window_length=self.sample_size , name=self.win_function , periodic=_lowerCamelCase ) a :str = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm='''slaney''' , mel_scale='''slaney''' , ) if frame_signal_scale != 1.0: warnings.warn( '''The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers''' , _lowerCamelCase , ) if reduction_factor != 2.0: warnings.warn( '''The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers''' , _lowerCamelCase , ) @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def SCREAMING_SNAKE_CASE__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 0.0 ): if attention_mask is not None: a :List[Any] = np.array(_lowerCamelCase , np.intaa ) a :List[str] = [] for vector, length in zip(_lowerCamelCase , attention_mask.sum(-1 ) ): a :Dict = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: a :Union[str, Any] = padding_value normed_input_values.append(_lowerCamelCase ) else: a :List[str] = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , ): a :Union[str, Any] = spectrogram( _lowerCamelCase , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel='''log10''' , ) return log_mel_spec.T def __call__( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , **_lowerCamelCase , ): if audio is None and audio_target is None: raise ValueError('''You must provide either `audio` or `audio_target` values.''' ) if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with''' F''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) if audio is not None: a :Optional[Any] = self._process_audio( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase , ) else: a :int = None if audio_target is not None: a :Optional[int] = self._process_audio( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase , ) if inputs is None: return inputs_target else: a :Optional[Any] = inputs_target['''input_values'''] a :Union[str, Any] = inputs_target.get('''attention_mask''' ) if decoder_attention_mask is not None: a :str = decoder_attention_mask return inputs def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , **_lowerCamelCase , ): a :Optional[int] = isinstance(_lowerCamelCase , np.ndarray ) and len(speech.shape ) > 1 if is_batched_numpy and len(speech.shape ) > 2: raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' ) a :List[Any] = is_batched_numpy or ( isinstance(_lowerCamelCase , (list, tuple) ) and (isinstance(speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: a :str = [np.asarray(_lowerCamelCase , dtype=np.floataa ) for speech in speech] elif not is_batched and not isinstance(_lowerCamelCase , np.ndarray ): a :Union[str, Any] = np.asarray(_lowerCamelCase , dtype=np.floataa ) elif isinstance(_lowerCamelCase , np.ndarray ) and speech.dtype is np.dtype(np.floataa ): a :List[Any] = speech.astype(np.floataa ) # always return batch if not is_batched: a :List[Any] = [speech] # needed to make pad() work on spectrogram inputs a :Optional[int] = self.feature_size # convert into correct format for padding if is_target: a :List[Any] = [self._extract_mel_features(_lowerCamelCase ) for waveform in speech] a :List[Any] = BatchFeature({'''input_values''': features} ) a :List[Any] = self.num_mel_bins else: a :List[str] = BatchFeature({'''input_values''': speech} ) a :Optional[int] = self.pad( _lowerCamelCase , padding=_lowerCamelCase , max_length=_lowerCamelCase , truncation=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , **_lowerCamelCase , ) a :List[str] = feature_size_hack # convert input values to correct format a :Tuple = padded_inputs['''input_values'''] if not isinstance(input_values[0] , np.ndarray ): a :int = [np.asarray(_lowerCamelCase , dtype=np.floataa ) for array in input_values] elif ( not isinstance(_lowerCamelCase , np.ndarray ) and isinstance(input_values[0] , np.ndarray ) and input_values[0].dtype is np.dtype(np.floataa ) ): a :Union[str, Any] = [array.astype(np.floataa ) for array in input_values] elif isinstance(_lowerCamelCase , np.ndarray ) and input_values.dtype is np.dtype(np.floataa ): a :Optional[int] = input_values.astype(np.floataa ) # convert attention_mask to correct format a :Any = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: a :Union[str, Any] = [np.asarray(_lowerCamelCase , dtype=np.intaa ) for array in attention_mask] # zero-mean and unit-variance normalization if not is_target and self.do_normalize: a :Union[str, Any] = ( attention_mask if self._get_padding_strategies(_lowerCamelCase , max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) a :List[str] = self.zero_mean_unit_var_norm( padded_inputs['''input_values'''] , attention_mask=_lowerCamelCase , padding_value=self.padding_value ) if return_tensors is not None: a :Any = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs def SCREAMING_SNAKE_CASE__ ( self ): a :List[str] = super().to_dict() # Don't serialize these as they are derived from the other properties. a :Tuple = ['''window''', '''mel_filters''', '''sample_size''', '''sample_stride''', '''n_fft''', '''n_freqs'''] for name in names: if name in output: del output[name] return output
94
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ,A_ : int ) -> Union[str, Any]: A = n A = [None] * self.n A = 0 # index of the first element A = 0 A = 0 def __len__( self : int ) -> int: return self.size def _SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.size == 0 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: return False if self.is_empty() else self.array[self.front] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ) -> int: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A = data A = (self.rear + 1) % self.n self.size += 1 return self def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) A = self.array[self.front] A = None A = (self.front + 1) % self.n self.size -= 1 return temp
74
0
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 DeformableDetrImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=[0.5, 0.5, 0.5] , lowerCAmelCase__=[0.5, 0.5, 0.5] , lowerCAmelCase__=True , lowerCAmelCase__=1 / 2_5_5 , lowerCAmelCase__=True , ) -> str: '''simple docstring''' a__ : str =size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} a__ : Tuple =parent a__ : Any =batch_size a__ : int =num_channels a__ : List[str] =min_resolution a__ : Tuple =max_resolution a__ : Tuple =do_resize a__ : Dict =size a__ : List[str] =do_normalize a__ : Optional[Any] =image_mean a__ : Tuple =image_std a__ : Dict =do_rescale a__ : List[Any] =rescale_factor a__ : Optional[Any] =do_pad def _lowercase ( self ) -> Any: '''simple docstring''' 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 _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=False ) -> Any: '''simple docstring''' if not batched: a__ : Tuple =image_inputs[0] if isinstance(lowerCAmelCase__ , Image.Image ): a__ , a__ : Union[str, Any] =image.size else: a__ , a__ : Optional[int] =image.shape[1], image.shape[2] if w < h: a__ : Optional[int] =int(self.size["shortest_edge"] * h / w ) a__ : List[Any] =self.size["shortest_edge"] elif w > h: a__ : Dict =self.size["shortest_edge"] a__ : List[Any] =int(self.size["shortest_edge"] * w / h ) else: a__ : List[Any] =self.size["shortest_edge"] a__ : int =self.size["shortest_edge"] else: a__ : List[Any] =[] for image in image_inputs: a__ , a__ : Optional[int] =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) a__ : Any =max(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : item[0] )[0] a__ : Union[str, Any] =max(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : Tuple = DeformableDetrImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =DeformableDetrImageProcessingTester(self ) @property def _lowercase ( self ) -> Dict: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[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__ , "do_rescale" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_pad" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : Optional[int] =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__ ) a__ : List[str] =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 _lowercase ( self ) -> Dict: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : List[Any] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : List[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 a__ , a__ : List[str] =self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__ ) a__ : Optional[int] =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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : 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 a__ : Union[str, Any] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : 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 a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , return_tensors="pt" ).pixel_values a__ , a__ : List[str] =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 _lowercase ( self ) -> int: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Union[str, 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 a__ : int =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : List[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 a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , return_tensors="pt" ).pixel_values a__ , a__ : Tuple =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, ) , ) @slow def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : int =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: a__ : Optional[int] =json.loads(f.read() ) a__ : Any ={"image_id": 3_9_7_6_9, "annotations": target} # encode them a__ : Union[str, Any] =DeformableDetrImageProcessor() a__ : Tuple =image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , return_tensors="pt" ) # verify pixel values a__ : Tuple =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__ ) a__ : Any =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4 ) ) # verify area a__ : List[Any] =torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__ ) ) # verify boxes a__ : Any =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__ ) a__ : Optional[Any] =torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3 ) ) # verify image_id a__ : int =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__ ) ) # verify is_crowd a__ : str =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__ ) ) # verify class_labels a__ : List[str] =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 a__ : Optional[int] =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__ ) ) # verify size a__ : int =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__ ) ) @slow def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : 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: a__ : int =json.loads(f.read() ) a__ : List[str] ={"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target} a__ : List[Any] =pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them a__ : Any =DeformableDetrImageProcessor(format="coco_panoptic" ) a__ : Optional[Any] =image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , masks_path=lowerCAmelCase__ , return_tensors="pt" ) # verify pixel values a__ : Union[str, Any] =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__ ) a__ : Union[str, Any] =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4 ) ) # verify area a__ : Dict =torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__ ) ) # verify boxes a__ : Optional[int] =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__ ) a__ : Any =torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3 ) ) # verify image_id a__ : int =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__ ) ) # verify is_crowd a__ : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__ ) ) # verify class_labels a__ : 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 a__ : int =8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCAmelCase__ ) # verify orig_size a__ : List[str] =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__ ) ) # verify size a__ : int =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__ ) )
95
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,*A_ : List[str] ,**A_ : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' ,A_ ,) super().__init__(*A_ ,**A_ )
74
0
"""simple docstring""" def _snake_case ( lowercase__ ): return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
96
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''gpt_bigcode''' _lowerCamelCase: List[Any] = ['''past_key_values'''] _lowerCamelCase: int = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Optional[int] ,A_ : Dict=5_0257 ,A_ : Union[str, Any]=1024 ,A_ : str=768 ,A_ : Any=12 ,A_ : Any=12 ,A_ : Optional[int]=None ,A_ : Any="gelu_pytorch_tanh" ,A_ : List[str]=0.1 ,A_ : Optional[int]=0.1 ,A_ : List[str]=0.1 ,A_ : Tuple=1e-5 ,A_ : Optional[int]=0.02 ,A_ : List[str]=True ,A_ : Optional[Any]=True ,A_ : List[Any]=5_0256 ,A_ : Union[str, Any]=5_0256 ,A_ : int=True ,A_ : Optional[Any]=True ,A_ : Dict=True ,**A_ : Union[str, Any] ,) -> Union[str, Any]: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = scale_attn_weights A = use_cache A = attention_softmax_in_fpaa A = scale_attention_softmax_in_fpaa A = multi_query A = bos_token_id A = eos_token_id super().__init__(bos_token_id=A_ ,eos_token_id=A_ ,**A_ )
74
0
'''simple docstring''' from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def a ( __a , __a , __a=1e-12 ) -> str: '''simple docstring''' UpperCamelCase__ :Optional[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T UpperCamelCase__ :Optional[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T return jnp.matmul(__a , norm_emb_a.T ) class lowercase ( nn.Module ): """simple docstring""" _a = 42 _a = jnp.floataa def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Optional[int] = FlaxCLIPVisionModule(self.config.vision_config ) UpperCamelCase__ :Tuple = nn.Dense(self.config.projection_dim , use_bias=UpperCamelCase_ , dtype=self.dtype ) UpperCamelCase__ :Optional[Any] = self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim) ) UpperCamelCase__ :Optional[Any] = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim) ) UpperCamelCase__ :Tuple = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,) ) UpperCamelCase__ :List[str] = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,) ) def __call__( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[str] = self.vision_model(UpperCamelCase_ )[1] UpperCamelCase__ :Optional[int] = self.visual_projection(UpperCamelCase_ ) UpperCamelCase__ :List[Any] = jax_cosine_distance(UpperCamelCase_ , self.special_care_embeds ) UpperCamelCase__ :List[str] = jax_cosine_distance(UpperCamelCase_ , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs UpperCamelCase__ :int = 0.0 UpperCamelCase__ :int = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment UpperCamelCase__ :Optional[int] = jnp.round(UpperCamelCase_ , 3 ) UpperCamelCase__ :Union[str, Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=UpperCamelCase_ ) # Use a lower threshold if an image has any special care concept UpperCamelCase__ :Union[str, Any] = is_special_care * 0.01 UpperCamelCase__ :List[str] = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment UpperCamelCase__ :Optional[int] = jnp.round(UpperCamelCase_ , 3 ) UpperCamelCase__ :int = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class lowercase ( A__ ): """simple docstring""" _a = CLIPConfig _a = 'clip_input' _a = FlaxStableDiffusionSafetyCheckerModule def __init__( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = 0 , UpperCamelCase_ = jnp.floataa , UpperCamelCase_ = True , **UpperCamelCase_ , ): '''simple docstring''' if input_shape is None: UpperCamelCase__ :Union[str, Any] = (1, 224, 224, 3) UpperCamelCase__ :Dict = self.module_class(config=UpperCamelCase_ , dtype=UpperCamelCase_ , **UpperCamelCase_ ) super().__init__(UpperCamelCase_ , UpperCamelCase_ , input_shape=UpperCamelCase_ , seed=UpperCamelCase_ , dtype=UpperCamelCase_ , _do_init=_do_init ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' UpperCamelCase__ :Dict = jax.random.normal(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase__ , UpperCamelCase__ :List[Any] = jax.random.split(UpperCamelCase_ ) UpperCamelCase__ :Tuple = {'''params''': params_rng, '''dropout''': dropout_rng} UpperCamelCase__ :List[str] = self.module.init(UpperCamelCase_ , UpperCamelCase_ )['''params'''] return random_params def __call__( self , UpperCamelCase_ , UpperCamelCase_ = None , ): '''simple docstring''' UpperCamelCase__ :Any = jnp.transpose(UpperCamelCase_ , (0, 2, 3, 1) ) return self.module.apply( {'''params''': params or self.params} , jnp.array(UpperCamelCase_ , dtype=jnp.floataa ) , rngs={} , )
97
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
0
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging lowerCAmelCase__ : Any = logging.get_logger(__name__) class snake_case ( __UpperCAmelCase ): """simple docstring""" snake_case__ = ["input_features"] def __init__( self : Optional[int] ,lowerCamelCase__ : Any=80 ,lowerCamelCase__ : Optional[Any]=16_000 ,lowerCamelCase__ : List[Any]=160 ,lowerCamelCase__ : int=30 ,lowerCamelCase__ : int=400 ,lowerCamelCase__ : Any=0.0 ,lowerCamelCase__ : Union[str, Any]=False ,**lowerCamelCase__ : Optional[Any] ,): super().__init__( feature_size=lowerCamelCase__ ,sampling_rate=lowerCamelCase__ ,padding_value=lowerCamelCase__ ,return_attention_mask=lowerCamelCase__ ,**lowerCamelCase__ ,) UpperCAmelCase__ = n_fft UpperCAmelCase__ = hop_length UpperCAmelCase__ = chunk_length UpperCAmelCase__ = chunk_length * sampling_rate UpperCAmelCase__ = self.n_samples // hop_length UpperCAmelCase__ = sampling_rate UpperCAmelCase__ = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 ,num_mel_filters=lowerCamelCase__ ,min_frequency=0.0 ,max_frequency=8_0_0_0.0 ,sampling_rate=lowerCamelCase__ ,norm='slaney' ,mel_scale='slaney' ,) def __lowerCAmelCase ( self : Any ,lowerCamelCase__ : np.array ): UpperCAmelCase__ = spectrogram( lowerCamelCase__ ,window_function(self.n_fft ,'hann' ) ,frame_length=self.n_fft ,hop_length=self.hop_length ,power=2.0 ,mel_filters=self.mel_filters ,log_mel='log10' ,) UpperCAmelCase__ = log_spec[:, :-1] UpperCAmelCase__ = np.maximum(lowerCamelCase__ ,log_spec.max() - 8.0 ) UpperCAmelCase__ = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def __lowerCAmelCase ( lowerCamelCase__ : List[np.ndarray] ,lowerCamelCase__ : List[np.ndarray] ,lowerCamelCase__ : float = 0.0 ): if attention_mask is not None: UpperCAmelCase__ = np.array(lowerCamelCase__ ,np.intaa ) UpperCAmelCase__ = [] for vector, length in zip(lowerCamelCase__ ,attention_mask.sum(-1 ) ): UpperCAmelCase__ = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: UpperCAmelCase__ = padding_value normed_input_values.append(lowerCamelCase__ ) else: UpperCAmelCase__ = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def __call__( self : int ,lowerCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,lowerCamelCase__ : bool = True ,lowerCamelCase__ : Optional[int] = None ,lowerCamelCase__ : Optional[Union[str, TensorType]] = None ,lowerCamelCase__ : Optional[bool] = None ,lowerCamelCase__ : Optional[str] = "max_length" ,lowerCamelCase__ : Optional[int] = None ,lowerCamelCase__ : Optional[int] = None ,lowerCamelCase__ : Optional[bool] = None ,**lowerCamelCase__ : Dict ,): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a''' f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input''' f''' was sampled with {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) UpperCAmelCase__ = isinstance(lowerCamelCase__ ,np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) UpperCAmelCase__ = is_batched_numpy or ( isinstance(lowerCamelCase__ ,(list, tuple) ) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list) )) ) if is_batched: UpperCAmelCase__ = [np.asarray([speech] ,dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(lowerCamelCase__ ,np.ndarray ): UpperCAmelCase__ = np.asarray(lowerCamelCase__ ,dtype=np.floataa ) elif isinstance(lowerCamelCase__ ,np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): UpperCAmelCase__ = raw_speech.astype(np.floataa ) # always return batch if not is_batched: UpperCAmelCase__ = [np.asarray([raw_speech] ).T] UpperCAmelCase__ = BatchFeature({'input_features': raw_speech} ) # convert into correct format for padding UpperCAmelCase__ = self.pad( lowerCamelCase__ ,padding=lowerCamelCase__ ,max_length=max_length if max_length else self.n_samples ,truncation=lowerCamelCase__ ,pad_to_multiple_of=lowerCamelCase__ ,return_attention_mask=return_attention_mask or do_normalize ,) # zero-mean and unit-variance normalization if do_normalize: UpperCAmelCase__ = self.zero_mean_unit_var_norm( padded_inputs['input_features'] ,attention_mask=padded_inputs['attention_mask'] ,padding_value=self.padding_value ,) UpperCAmelCase__ = np.stack(padded_inputs['input_features'] ,axis=0 ) # make sure list is in array format UpperCAmelCase__ = padded_inputs.get('input_features' ).transpose(2 ,0 ,1 ) UpperCAmelCase__ = [self._np_extract_fbank_features(lowerCamelCase__ ) for waveform in input_features[0]] if isinstance(input_features[0] ,lowerCamelCase__ ): UpperCAmelCase__ = [np.asarray(lowerCamelCase__ ,dtype=np.floataa ) for feature in input_features] else: UpperCAmelCase__ = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) UpperCAmelCase__ = padded_inputs['attention_mask'][:, :: self.hop_length] if return_tensors is not None: UpperCAmelCase__ = padded_inputs.convert_to_tensors(lowerCamelCase__ ) return padded_inputs def __lowerCAmelCase ( self : Tuple ): UpperCAmelCase__ = copy.deepcopy(self.__dict__ ) UpperCAmelCase__ = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
98
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
0
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated lowercase : List[Any] = collections.namedtuple("""_Datasets""", ["""train""", """validation""", """test"""]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ lowercase : Any = """https://storage.googleapis.com/cvdf-datasets/mnist/""" def A_ ( A__ ) -> str: a__ : Optional[Any] = numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=A__ )[0] @deprecated(A__ , 'Please use tf.data to implement this functionality.' ) def A_ ( A__ ) -> Optional[Any]: print('Extracting' , f.name ) with gzip.GzipFile(fileobj=A__ ) as bytestream: a__ : Dict = _readaa(A__ ) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) a__ : Optional[Any] = _readaa(A__ ) a__ : Union[str, Any] = _readaa(A__ ) a__ : Tuple = _readaa(A__ ) a__ : Any = bytestream.read(rows * cols * num_images ) a__ : List[Any] = numpy.frombuffer(A__ , dtype=numpy.uinta ) a__ : Any = data.reshape(A__ , A__ , A__ , 1 ) return data @deprecated(A__ , 'Please use tf.one_hot on tensors.' ) def A_ ( A__ , A__ ) -> Union[str, Any]: a__ : str = labels_dense.shape[0] a__ : Union[str, Any] = numpy.arange(A__ ) * num_classes a__ : Any = numpy.zeros((num_labels, num_classes) ) a__ : int = 1 return labels_one_hot @deprecated(A__ , 'Please use tf.data to implement this functionality.' ) def A_ ( A__ , A__=False , A__=10 ) -> Optional[Any]: print('Extracting' , f.name ) with gzip.GzipFile(fileobj=A__ ) as bytestream: a__ : Optional[int] = _readaa(A__ ) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) a__ : Optional[int] = _readaa(A__ ) a__ : Any = bytestream.read(A__ ) a__ : Tuple = numpy.frombuffer(A__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(A__ , A__ ) return labels class A__ : """simple docstring""" @deprecated( lowercase , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , lowercase , lowercase , lowercase=False , lowercase=False , lowercase=dtypes.floataa , lowercase=True , lowercase=None , ) -> Optional[int]: '''simple docstring''' a__ , a__ : int = random_seed.get_seed(lowercase) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda) a__ : Union[str, Any] = dtypes.as_dtype(lowercase).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype) if fake_data: a__ : str = 1_0000 a__ : Optional[int] = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F'images.shape: {images.shape} labels.shape: {labels.shape}' a__ : List[str] = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 a__ : str = images.reshape( images.shape[0] , images.shape[1] * images.shape[2]) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. a__ : Tuple = images.astype(numpy.floataa) a__ : List[str] = numpy.multiply(lowercase , 1.0 / 2_55.0) a__ : Optional[int] = images a__ : Tuple = labels a__ : Any = 0 a__ : Dict = 0 @property def __lowercase ( self) -> str: '''simple docstring''' return self._images @property def __lowercase ( self) -> Tuple: '''simple docstring''' return self._labels @property def __lowercase ( self) -> Tuple: '''simple docstring''' return self._num_examples @property def __lowercase ( self) -> Any: '''simple docstring''' return self._epochs_completed def __lowercase ( self , lowercase , lowercase=False , lowercase=True) -> Union[str, Any]: '''simple docstring''' if fake_data: a__ : Dict = [1] * 784 a__ : List[Any] = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(lowercase)], [fake_label for _ in range(lowercase)], ) a__ : Dict = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: a__ : Optional[int] = numpy.arange(self._num_examples) numpy.random.shuffle(lowercase) a__ : List[str] = self.images[perma] a__ : str = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch a__ : Union[str, Any] = self._num_examples - start a__ : Optional[int] = self._images[start : self._num_examples] a__ : Any = self._labels[start : self._num_examples] # Shuffle the data if shuffle: a__ : List[str] = numpy.arange(self._num_examples) numpy.random.shuffle(lowercase) a__ : List[str] = self.images[perm] a__ : str = self.labels[perm] # Start next epoch a__ : List[Any] = 0 a__ : Tuple = batch_size - rest_num_examples a__ : str = self._index_in_epoch a__ : Optional[Any] = self._images[start:end] a__ : List[str] = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0), ) else: self._index_in_epoch += batch_size a__ : str = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(A__ , 'Please write your own downloading logic.' ) def A_ ( A__ , A__ , A__ ) -> Dict: if not gfile.Exists(A__ ): gfile.MakeDirs(A__ ) a__ : Union[str, Any] = os.path.join(A__ , A__ ) if not gfile.Exists(A__ ): urllib.request.urlretrieve(A__ , A__ ) # noqa: S310 with gfile.GFile(A__ ) as f: a__ : Optional[Any] = f.size() print('Successfully downloaded' , A__ , A__ , 'bytes.' ) return filepath @deprecated( A__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def A_ ( A__ , A__=False , A__=False , A__=dtypes.floataa , A__=True , A__=5000 , A__=None , A__=DEFAULT_SOURCE_URL , ) -> List[Any]: if fake_data: def fake(): return _DataSet( [] , [] , fake_data=A__ , one_hot=A__ , dtype=A__ , seed=A__ ) a__ : List[str] = fake() a__ : int = fake() a__ : str = fake() return _Datasets(train=A__ , validation=A__ , test=A__ ) if not source_url: # empty string check a__ : List[str] = DEFAULT_SOURCE_URL a__ : Tuple = 'train-images-idx3-ubyte.gz' a__ : str = 'train-labels-idx1-ubyte.gz' a__ : str = 't10k-images-idx3-ubyte.gz' a__ : List[Any] = 't10k-labels-idx1-ubyte.gz' a__ : Dict = _maybe_download( A__ , A__ , source_url + train_images_file ) with gfile.Open(A__ , 'rb' ) as f: a__ : Union[str, Any] = _extract_images(A__ ) a__ : Any = _maybe_download( A__ , A__ , source_url + train_labels_file ) with gfile.Open(A__ , 'rb' ) as f: a__ : List[Any] = _extract_labels(A__ , one_hot=A__ ) a__ : Union[str, Any] = _maybe_download( A__ , A__ , source_url + test_images_file ) with gfile.Open(A__ , 'rb' ) as f: a__ : Optional[Any] = _extract_images(A__ ) a__ : List[Any] = _maybe_download( A__ , A__ , source_url + test_labels_file ) with gfile.Open(A__ , 'rb' ) as f: a__ : List[str] = _extract_labels(A__ , one_hot=A__ ) if not 0 <= validation_size <= len(A__ ): a__ : str = ( 'Validation size should be between 0 and ' F'{len(A__ )}. Received: {validation_size}.' ) raise ValueError(A__ ) a__ : Union[str, Any] = train_images[:validation_size] a__ : str = train_labels[:validation_size] a__ : Optional[int] = train_images[validation_size:] a__ : str = train_labels[validation_size:] a__ : Optional[int] = {'dtype': dtype, 'reshape': reshape, 'seed': seed} a__ : Dict = _DataSet(A__ , A__ , **A__ ) a__ : Union[str, Any] = _DataSet(A__ , A__ , **A__ ) a__ : Dict = _DataSet(A__ , A__ , **A__ ) return _Datasets(train=A__ , validation=A__ , test=A__ )
99
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _snake_case ( snake_case__ : List[Any] , snake_case__ : Optional[int]=0.999 , snake_case__ : Union[str, Any]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) A = [] for i in range(snake_case__ ): A = i / num_diffusion_timesteps A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class lowerCAmelCase_ ( _lowercase , _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [e.name for e in KarrasDiffusionSchedulers] _lowerCamelCase: Optional[Any] = 2 @register_to_config def __init__( self : str ,A_ : int = 1000 ,A_ : float = 0.0_00_85 ,A_ : float = 0.0_12 ,A_ : str = "linear" ,A_ : Optional[Union[np.ndarray, List[float]]] = None ,A_ : str = "epsilon" ,A_ : Optional[bool] = False ,A_ : Optional[bool] = False ,A_ : float = 1.0 ,A_ : str = "linspace" ,A_ : int = 0 ,) -> List[str]: if trained_betas is not None: A = torch.tensor(A_ ,dtype=torch.floataa ) elif beta_schedule == "linear": A = torch.linspace(A_ ,A_ ,A_ ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A_ ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A = betas_for_alpha_bar(A_ ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": A = betas_for_alpha_bar(A_ ,alpha_transform_type='exp' ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) A = 1.0 - self.betas A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A_ ,A_ ,A_ ) A = use_karras_sigmas def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ,A_ : Tuple=None ) -> Tuple: if schedule_timesteps is None: A = self.timesteps A = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A = 1 if len(A_ ) > 1 else 0 else: A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep A = self._index_counter[timestep_int] return indices[pos].item() @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : torch.FloatTensor ,A_ : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: A = self.index_for_timestep(A_ ) A = self.sigmas[step_index] A = sample / ((sigma**2 + 1) ** 0.5) return sample def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : Union[str, torch.device] = None ,A_ : Optional[int] = None ,) -> Optional[Any]: A = num_inference_steps A = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A = np.linspace(0 ,num_train_timesteps - 1 ,A_ ,dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": A = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(0 ,A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A = (np.arange(A_ ,0 ,-step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A = np.log(A_ ) A = np.interp(A_ ,np.arange(0 ,len(A_ ) ) ,A_ ) if self.config.use_karras_sigmas: A = self._convert_to_karras(in_sigmas=A_ ,num_inference_steps=self.num_inference_steps ) A = np.array([self._sigma_to_t(A_ ,A_ ) for sigma in sigmas] ) A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A = torch.from_numpy(A_ ).to(device=A_ ) A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A = torch.from_numpy(A_ ) A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(A_ ).startswith('mps' ): # mps does not support float64 A = timesteps.to(A_ ,dtype=torch.floataa ) else: A = timesteps.to(device=A_ ) # empty dt and derivative A = None A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A = defaultdict(A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[Any] ,A_ : List[str] ) -> Dict: # get log sigma A = np.log(A_ ) # get distribution A = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A = low_idx + 1 A = log_sigmas[low_idx] A = log_sigmas[high_idx] # interpolate sigmas A = (low - log_sigma) / (low - high) A = np.clip(A_ ,0 ,1 ) # transform interpolation to time range A = (1 - w) * low_idx + w * high_idx A = t.reshape(sigma.shape ) return t def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : torch.FloatTensor ,A_ : int ) -> torch.FloatTensor: A = in_sigmas[-1].item() A = in_sigmas[0].item() A = 7.0 # 7.0 is the value used in the paper A = np.linspace(0 ,1 ,A_ ) A = sigma_min ** (1 / rho) A = sigma_max ** (1 / rho) A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: return self.dt is None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : Union[float, torch.FloatTensor] ,A_ : Union[torch.FloatTensor, np.ndarray] ,A_ : bool = True ,) -> Union[SchedulerOutput, Tuple]: A = self.index_for_timestep(A_ ) # advance index counter by 1 A = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A = self.sigmas[step_index] A = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A = self.sigmas[step_index - 1] A = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A = 0 A = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A = sigma_hat if self.state_in_first_order else sigma_next A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A = sigma_hat if self.state_in_first_order else sigma_next A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A = model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: A = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A = sigma_next - sigma_hat # store for 2nd order step A = derivative A = dt A = sample else: # 2. 2nd order / Heun's method A = (sample - pred_original_sample) / sigma_next A = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A = self.dt A = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A = None A = None A = None A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,A_ : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: A = self.timesteps.to(original_samples.device ) A = timesteps.to(original_samples.device ) A = [self.index_for_timestep(A_ ,A_ ) for t in timesteps] A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A = sigma.unsqueeze(-1 ) A = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ) -> int: return self.config.num_train_timesteps
74
0
"""simple docstring""" import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ.get("LOGLEVEL", "INFO").upper(), stream=sys.stdout, ) __magic_name__ = logging.getLogger(__name__) __magic_name__ = {"facebook/bart-base": BartForConditionalGeneration} __magic_name__ = {"facebook/bart-base": BartTokenizer} def _lowerCAmelCase ( ): __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Export Bart model + Beam Search to ONNX graph.""" ) parser.add_argument( """--validation_file""" , type=UpperCamelCase_ , default=UpperCamelCase_ , help="""A csv or a json file containing the validation data.""" ) parser.add_argument( """--max_length""" , type=UpperCamelCase_ , default=5 , help="""The maximum total input sequence length after tokenization.""" , ) parser.add_argument( """--num_beams""" , type=UpperCamelCase_ , default=UpperCamelCase_ , help=( """Number of beams to use for evaluation. This argument will be """ """passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.""" ) , ) parser.add_argument( """--model_name_or_path""" , type=UpperCamelCase_ , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=UpperCamelCase_ , ) parser.add_argument( """--config_name""" , type=UpperCamelCase_ , default=UpperCamelCase_ , help="""Pretrained config name or path if not the same as model_name""" , ) parser.add_argument( """--device""" , type=UpperCamelCase_ , default="""cpu""" , help="""Device where the model will be run""" , ) parser.add_argument("""--output_file_path""" , type=UpperCamelCase_ , default=UpperCamelCase_ , help="""Where to store the final ONNX file.""" ) __SCREAMING_SNAKE_CASE = parser.parse_args() return args def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_="cpu" ): __SCREAMING_SNAKE_CASE = model_dict[model_name].from_pretrained(UpperCamelCase_ ).to(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = tokenizer_dict[model_name].from_pretrained(UpperCamelCase_ ) if model_name in ["facebook/bart-base"]: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = 0 return huggingface_model, tokenizer def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): model.eval() __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = torch.jit.script(BARTBeamSearchGenerator(UpperCamelCase_ ) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = """My friends are cool but they eat too many carbs.""" __SCREAMING_SNAKE_CASE = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="""pt""" ).to(model.device ) __SCREAMING_SNAKE_CASE = model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , num_beams=UpperCamelCase_ , max_length=UpperCamelCase_ , early_stopping=UpperCamelCase_ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( UpperCamelCase_ , ( inputs["""input_ids"""], inputs["""attention_mask"""], num_beams, max_length, model.config.decoder_start_token_id, ) , UpperCamelCase_ , opset_version=14 , input_names=["""input_ids""", """attention_mask""", """num_beams""", """max_length""", """decoder_start_token_id"""] , output_names=["""output_ids"""] , dynamic_axes={ """input_ids""": {0: """batch""", 1: """seq"""}, """output_ids""": {0: """batch""", 1: """seq_out"""}, } , example_outputs=UpperCamelCase_ , ) logger.info("""Model exported to {}""".format(UpperCamelCase_ ) ) __SCREAMING_SNAKE_CASE = remove_dup_initializers(os.path.abspath(UpperCamelCase_ ) ) logger.info("""Deduplicated and optimized model written to {}""".format(UpperCamelCase_ ) ) __SCREAMING_SNAKE_CASE = onnxruntime.InferenceSession(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = ort_sess.run( UpperCamelCase_ , { """input_ids""": inputs["""input_ids"""].cpu().numpy(), """attention_mask""": inputs["""attention_mask"""].cpu().numpy(), """num_beams""": np.array(UpperCamelCase_ ), """max_length""": np.array(UpperCamelCase_ ), """decoder_start_token_id""": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3 ) logger.info("""Model outputs from torch and ONNX Runtime are similar.""" ) logger.info("""Success.""" ) def _lowerCAmelCase ( ): __SCREAMING_SNAKE_CASE = parse_args() __SCREAMING_SNAKE_CASE = 5 __SCREAMING_SNAKE_CASE = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() __SCREAMING_SNAKE_CASE = torch.device(args.device ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = load_model_tokenizer(args.model_name_or_path , UpperCamelCase_ ) if model.config.decoder_start_token_id is None: raise ValueError("""Make sure that `config.decoder_start_token_id` is correctly defined""" ) model.to(UpperCamelCase_ ) if args.max_length: __SCREAMING_SNAKE_CASE = args.max_length if args.num_beams: __SCREAMING_SNAKE_CASE = args.num_beams if args.output_file_path: __SCREAMING_SNAKE_CASE = args.output_file_path else: __SCREAMING_SNAKE_CASE = """BART.onnx""" logger.info("""Exporting model to ONNX""" ) export_and_validate_model(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if __name__ == "__main__": main()
100
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Dict ,A_ : list[int] ) -> None: A = len(A_ ) A = [0] * len_array if len_array > 0: A = array[0] for i in range(1 ,A_ ): A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ,A_ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : str ,A_ : int ) -> bool: A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(A_ ) return False if __name__ == "__main__": import doctest doctest.testmod()
74
0
from __future__ import annotations import numpy as np def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' return np.maximum(0 , lowerCAmelCase__ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
101
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowercase = logging.get_logger(__name__) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = RobertaPreLayerNormConfig.from_pretrained( snake_case__ , architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict A = torch.load(hf_hub_download(repo_id=snake_case__ , filename='pytorch_model.bin' ) ) A = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): A = 'roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue A = tensor_value A = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=snake_case__ , config=snake_case__ , state_dict=snake_case__ ) model.save_pretrained(snake_case__ ) # convert tokenizer A = AutoTokenizer.from_pretrained(snake_case__ ) tokenizer.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
74
0
"""simple docstring""" from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig SCREAMING_SNAKE_CASE : Optional[Any] = { """susnato/ernie-m-base_pytorch""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json""", """susnato/ernie-m-large_pytorch""": """https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json""", } class _UpperCAmelCase ( __snake_case ): '''simple docstring''' lowerCamelCase__ ='ernie_m' lowerCamelCase__ ={"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__(self , a_ = 25_00_02 , a_ = 7_68 , a_ = 12 , a_ = 12 , a_ = 30_72 , a_ = "gelu" , a_ = 0.1 , a_ = 0.1 , a_ = 5_14 , a_ = 0.02 , a_ = 1 , a_ = 1E-05 , a_=None , a_=False , a_=0.0 , **a_ , ): '''simple docstring''' super().__init__(pad_token_id=a_ , **a_ ) __snake_case : Union[str, Any] = vocab_size __snake_case : Optional[Any] = hidden_size __snake_case : Optional[Any] = num_hidden_layers __snake_case : List[Any] = num_attention_heads __snake_case : Optional[int] = intermediate_size __snake_case : Union[str, Any] = hidden_act __snake_case : Optional[Any] = hidden_dropout_prob __snake_case : int = attention_probs_dropout_prob __snake_case : Union[str, Any] = max_position_embeddings __snake_case : Optional[Any] = initializer_range __snake_case : Any = layer_norm_eps __snake_case : str = classifier_dropout __snake_case : Optional[int] = is_decoder __snake_case : Optional[int] = act_dropout
102
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''roformer''' def __init__( self : Tuple ,A_ : Optional[int]=5_0000 ,A_ : Tuple=None ,A_ : Optional[Any]=768 ,A_ : Dict=12 ,A_ : Optional[int]=12 ,A_ : Union[str, Any]=3072 ,A_ : Dict="gelu" ,A_ : Dict=0.1 ,A_ : List[Any]=0.1 ,A_ : List[Any]=1536 ,A_ : List[str]=2 ,A_ : Any=0.02 ,A_ : str=1e-12 ,A_ : Optional[int]=0 ,A_ : List[str]=False ,A_ : Tuple=True ,**A_ : List[str] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size if embedding_size is None else embedding_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = rotary_value A = use_cache class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: A = {0: 'batch', 1: 'sequence'} A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
74
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def UpperCamelCase( __UpperCamelCase : Union[str, Any] ): lowerCAmelCase_ : Any = 384 if "tiny" in model_name: lowerCAmelCase_ : Tuple = [3, 3, 9, 3] lowerCAmelCase_ : List[str] = [96, 192, 384, 768] if "small" in model_name: lowerCAmelCase_ : List[Any] = [3, 3, 27, 3] lowerCAmelCase_ : List[str] = [96, 192, 384, 768] if "base" in model_name: lowerCAmelCase_ : Optional[int] = [3, 3, 27, 3] lowerCAmelCase_ : List[str] = [128, 256, 512, 1024] lowerCAmelCase_ : int = 512 if "large" in model_name: lowerCAmelCase_ : List[str] = [3, 3, 27, 3] lowerCAmelCase_ : int = [192, 384, 768, 1536] lowerCAmelCase_ : List[Any] = 768 if "xlarge" in model_name: lowerCAmelCase_ : Optional[Any] = [3, 3, 27, 3] lowerCAmelCase_ : Optional[int] = [256, 512, 1024, 2048] lowerCAmelCase_ : Optional[Any] = 1024 # set label information lowerCAmelCase_ : Tuple = 150 lowerCAmelCase_ : Optional[int] = '''huggingface/label-files''' lowerCAmelCase_ : str = '''ade20k-id2label.json''' lowerCAmelCase_ : List[str] = json.load(open(hf_hub_download(__UpperCamelCase ,__UpperCamelCase ,repo_type='''dataset''' ) ,'''r''' ) ) lowerCAmelCase_ : Any = {int(__UpperCamelCase ): v for k, v in idalabel.items()} lowerCAmelCase_ : Optional[int] = {v: k for k, v in idalabel.items()} lowerCAmelCase_ : Dict = ConvNextConfig( depths=__UpperCamelCase ,hidden_sizes=__UpperCamelCase ,out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) lowerCAmelCase_ : List[Any] = UperNetConfig( backbone_config=__UpperCamelCase ,auxiliary_in_channels=__UpperCamelCase ,num_labels=__UpperCamelCase ,idalabel=__UpperCamelCase ,labelaid=__UpperCamelCase ,) return config def UpperCamelCase( __UpperCamelCase : List[Any] ): lowerCAmelCase_ : List[str] = [] # fmt: off # stem rename_keys.append(('''backbone.downsample_layers.0.0.weight''', '''backbone.embeddings.patch_embeddings.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.0.bias''', '''backbone.embeddings.patch_embeddings.bias''') ) rename_keys.append(('''backbone.downsample_layers.0.1.weight''', '''backbone.embeddings.layernorm.weight''') ) rename_keys.append(('''backbone.downsample_layers.0.1.bias''', '''backbone.embeddings.layernorm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"""backbone.stages.{i}.{j}.gamma""", f"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.norm.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.norm.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") ) if i > 0: rename_keys.append((f"""backbone.downsample_layers.{i}.0.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.0.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.1.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.1.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""") ) rename_keys.append((f"""backbone.norm{i}.weight""", f"""backbone.hidden_states_norms.stage{i+1}.weight""") ) rename_keys.append((f"""backbone.norm{i}.bias""", f"""backbone.hidden_states_norms.stage{i+1}.bias""") ) # decode head rename_keys.extend( [ ('''decode_head.conv_seg.weight''', '''decode_head.classifier.weight'''), ('''decode_head.conv_seg.bias''', '''decode_head.classifier.bias'''), ('''auxiliary_head.conv_seg.weight''', '''auxiliary_head.classifier.weight'''), ('''auxiliary_head.conv_seg.bias''', '''auxiliary_head.classifier.bias'''), ] ) # fmt: on return rename_keys def UpperCamelCase( __UpperCamelCase : int ,__UpperCamelCase : Optional[Any] ,__UpperCamelCase : Tuple ): lowerCAmelCase_ : Any = dct.pop(__UpperCamelCase ) lowerCAmelCase_ : Tuple = val def UpperCamelCase( __UpperCamelCase : Optional[int] ,__UpperCamelCase : int ,__UpperCamelCase : Dict ): lowerCAmelCase_ : List[Any] = { '''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''', '''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''', '''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''', '''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''', '''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''', } lowerCAmelCase_ : str = model_name_to_url[model_name] lowerCAmelCase_ : str = torch.hub.load_state_dict_from_url(__UpperCamelCase ,map_location='''cpu''' )['''state_dict'''] lowerCAmelCase_ : Optional[int] = get_upernet_config(__UpperCamelCase ) lowerCAmelCase_ : Any = UperNetForSemanticSegmentation(__UpperCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): lowerCAmelCase_ : Dict = state_dict.pop(__UpperCamelCase ) if "bn" in key: lowerCAmelCase_ : List[str] = key.replace('''bn''' ,'''batch_norm''' ) lowerCAmelCase_ : Tuple = val # rename keys lowerCAmelCase_ : str = create_rename_keys(__UpperCamelCase ) for src, dest in rename_keys: rename_key(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) # verify on image lowerCAmelCase_ : int = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' lowerCAmelCase_ : Tuple = Image.open(requests.get(__UpperCamelCase ,stream=__UpperCamelCase ).raw ).convert('''RGB''' ) lowerCAmelCase_ : Dict = SegformerImageProcessor() lowerCAmelCase_ : Any = processor(__UpperCamelCase ,return_tensors='''pt''' ).pixel_values with torch.no_grad(): lowerCAmelCase_ : str = model(__UpperCamelCase ) if model_name == "upernet-convnext-tiny": lowerCAmelCase_ : List[str] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ) elif model_name == "upernet-convnext-small": lowerCAmelCase_ : Union[str, Any] = torch.tensor( [[-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.7_6_3_8, -8.7_6_3_8, -8.6_2_4_0]] ) elif model_name == "upernet-convnext-base": lowerCAmelCase_ : Dict = torch.tensor( [[-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.7_6_6_9, -8.7_6_6_9, -8.6_0_2_1]] ) elif model_name == "upernet-convnext-large": lowerCAmelCase_ : Optional[Any] = torch.tensor( [[-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_3_1_0, -8.6_3_1_0, -8.5_9_6_4]] ) elif model_name == "upernet-convnext-xlarge": lowerCAmelCase_ : Dict = torch.tensor( [[-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_3_7_9, -8.4_3_7_9, -8.3_4_1_2]] ) print('''Logits:''' ,outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] ,__UpperCamelCase ,atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(__UpperCamelCase ) if push_to_hub: print(f"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(f"""openmmlab/{model_name}""" ) processor.push_to_hub(f"""openmmlab/{model_name}""" ) if __name__ == "__main__": A__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''upernet-convnext-tiny''', type=str, choices=[F'''upernet-convnext-{size}''' for size in ['''tiny''', '''small''', '''base''', '''large''', '''xlarge''']], help='''Name of the ConvNext UperNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) A__ : int = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
103
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _snake_case ( snake_case__ : Dict ): A = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def _snake_case ( snake_case__ : int ): A , A = emb.weight.shape A = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) A = emb.weight.data return lin_layer def _snake_case ( snake_case__ : List[str] , snake_case__ : Any="facebook/mbart-large-en-ro" , snake_case__ : Optional[int]=False , snake_case__ : List[str]=False ): A = torch.load(snake_case__ , map_location='cpu' )['model'] remove_ignore_keys_(snake_case__ ) A = state_dict['encoder.embed_tokens.weight'].shape[0] A = MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: A = 'relu' A = state_dict['decoder.embed_tokens.weight'] A = MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: A = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowercase = 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''') _lowercase = parser.parse_args() _lowercase = 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)
74
0
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os 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 lowerCAmelCase__ = '''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 _A ( ): """simple docstring""" __lowercase = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __lowercase = get_sagemaker_input() else: __lowercase = get_cluster_input() return config def _A ( A__=None ): """simple docstring""" if subparsers is not None: __lowercase = subparsers.add_parser('''config''' , description=A__ ) else: __lowercase = argparse.ArgumentParser('''Accelerate config command''' , description=A__ ) parser.add_argument( '''--config_file''' , default=A__ , 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=A__ ) return parser def _A ( A__ ): """simple docstring""" __lowercase = get_user_input() if args.config_file is not None: __lowercase = args.config_file else: if not os.path.isdir(A__ ): os.makedirs(A__ ) __lowercase = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(A__ ) else: config.to_yaml_file(A__ ) print(F"accelerate configuration saved at {config_file}" ) def _A ( ): """simple docstring""" __lowercase = config_command_parser() __lowercase = parser.parse_args() config_command(A__ ) if __name__ == "__main__": main()
104
"""simple docstring""" import argparse import struct import unittest class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Tuple ,A_ : bytes ) -> None: A = data # Initialize hash values A = [ 0X6_A_0_9_E_6_6_7, 0XB_B_6_7_A_E_8_5, 0X3_C_6_E_F_3_7_2, 0XA_5_4_F_F_5_3_A, 0X5_1_0_E_5_2_7_F, 0X9_B_0_5_6_8_8_C, 0X1_F_8_3_D_9_A_B, 0X5_B_E_0_C_D_1_9, ] # Initialize round constants A = [ 0X4_2_8_A_2_F_9_8, 0X7_1_3_7_4_4_9_1, 0XB_5_C_0_F_B_C_F, 0XE_9_B_5_D_B_A_5, 0X3_9_5_6_C_2_5_B, 0X5_9_F_1_1_1_F_1, 0X9_2_3_F_8_2_A_4, 0XA_B_1_C_5_E_D_5, 0XD_8_0_7_A_A_9_8, 0X1_2_8_3_5_B_0_1, 0X2_4_3_1_8_5_B_E, 0X5_5_0_C_7_D_C_3, 0X7_2_B_E_5_D_7_4, 0X8_0_D_E_B_1_F_E, 0X9_B_D_C_0_6_A_7, 0XC_1_9_B_F_1_7_4, 0XE_4_9_B_6_9_C_1, 0XE_F_B_E_4_7_8_6, 0X0_F_C_1_9_D_C_6, 0X2_4_0_C_A_1_C_C, 0X2_D_E_9_2_C_6_F, 0X4_A_7_4_8_4_A_A, 0X5_C_B_0_A_9_D_C, 0X7_6_F_9_8_8_D_A, 0X9_8_3_E_5_1_5_2, 0XA_8_3_1_C_6_6_D, 0XB_0_0_3_2_7_C_8, 0XB_F_5_9_7_F_C_7, 0XC_6_E_0_0_B_F_3, 0XD_5_A_7_9_1_4_7, 0X0_6_C_A_6_3_5_1, 0X1_4_2_9_2_9_6_7, 0X2_7_B_7_0_A_8_5, 0X2_E_1_B_2_1_3_8, 0X4_D_2_C_6_D_F_C, 0X5_3_3_8_0_D_1_3, 0X6_5_0_A_7_3_5_4, 0X7_6_6_A_0_A_B_B, 0X8_1_C_2_C_9_2_E, 0X9_2_7_2_2_C_8_5, 0XA_2_B_F_E_8_A_1, 0XA_8_1_A_6_6_4_B, 0XC_2_4_B_8_B_7_0, 0XC_7_6_C_5_1_A_3, 0XD_1_9_2_E_8_1_9, 0XD_6_9_9_0_6_2_4, 0XF_4_0_E_3_5_8_5, 0X1_0_6_A_A_0_7_0, 0X1_9_A_4_C_1_1_6, 0X1_E_3_7_6_C_0_8, 0X2_7_4_8_7_7_4_C, 0X3_4_B_0_B_C_B_5, 0X3_9_1_C_0_C_B_3, 0X4_E_D_8_A_A_4_A, 0X5_B_9_C_C_A_4_F, 0X6_8_2_E_6_F_F_3, 0X7_4_8_F_8_2_E_E, 0X7_8_A_5_6_3_6_F, 0X8_4_C_8_7_8_1_4, 0X8_C_C_7_0_2_0_8, 0X9_0_B_E_F_F_F_A, 0XA_4_5_0_6_C_E_B, 0XB_E_F_9_A_3_F_7, 0XC_6_7_1_7_8_F_2, ] A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : bytes ) -> bytes: A = B'\x80' + (B'\x00' * (63 - (len(A_ ) + 8) % 64)) A = struct.pack('>Q' ,(len(A_ ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: # Convert into blocks of 64 bytes A = [ self.preprocessed_data[x : x + 64] for x in range(0 ,len(self.preprocessed_data ) ,64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers A = list(struct.unpack('>16L' ,A_ ) ) # add 48 0-ed integers words += [0] * 48 A , A , A , A , A , A , A , A = self.hashes for index in range(0 ,64 ): if index > 15: # modify the zero-ed indexes at the end of the array A = ( self.ror(words[index - 15] ,7 ) ^ self.ror(words[index - 15] ,18 ) ^ (words[index - 15] >> 3) ) A = ( self.ror(words[index - 2] ,17 ) ^ self.ror(words[index - 2] ,19 ) ^ (words[index - 2] >> 10) ) A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0_0_0_0_0_0_0_0 # Compression A = self.ror(A_ ,6 ) ^ self.ror(A_ ,11 ) ^ self.ror(A_ ,25 ) A = (e & f) ^ ((~e & 0XF_F_F_F_F_F_F_F) & g) A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0_0_0_0_0_0_0_0 A = self.ror(A_ ,2 ) ^ self.ror(A_ ,13 ) ^ self.ror(A_ ,22 ) A = (a & b) ^ (a & c) ^ (b & c) A = (sa + maj) % 0X1_0_0_0_0_0_0_0_0 A , A , A , A , A , A , A , A = ( g, f, e, ((d + tempa) % 0X1_0_0_0_0_0_0_0_0), c, b, a, ((tempa + tempa) % 0X1_0_0_0_0_0_0_0_0), ) A = [a, b, c, d, e, f, g, h] # Modify final values A = [ ((element + mutated_hash_values[index]) % 0X1_0_0_0_0_0_0_0_0) for index, element in enumerate(self.hashes ) ] A = ''.join([hex(A_ )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : int ) -> int: return 0XF_F_F_F_F_F_F_F & (value << (32 - rotations)) | (value >> rotations) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> None: import hashlib A = bytes('Test String' ,'utf-8' ) self.assertEqual(SHAaaa(A_ ).hash ,hashlib.shaaaa(A_ ).hexdigest() ) def _snake_case ( ): import doctest doctest.testmod() A = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) A = parser.parse_args() A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: A = f.read() else: A = bytes(snake_case__ , 'utf-8' ) print(SHAaaa(snake_case__ ).hash ) if __name__ == "__main__": main()
74
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a : str = {'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Any = ['''YolosFeatureExtractor'''] a : List[str] = ['''YolosImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : List[str] = [ '''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''YolosForObjectDetection''', '''YolosModel''', '''YolosPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys a : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
105
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = ['''DeiTFeatureExtractor'''] _lowercase = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDeiTForImageClassification''', '''TFDeiTForImageClassificationWithTeacher''', '''TFDeiTForMaskedImageModeling''', '''TFDeiTModel''', '''TFDeiTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
74
0
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( a_ , unittest.TestCase ): """simple docstring""" lowercase__ = AudioLDMPipeline lowercase__ = TEXT_TO_AUDIO_PARAMS lowercase__ = TEXT_TO_AUDIO_BATCH_PARAMS lowercase__ = frozenset( [ "num_inference_steps", "num_waveforms_per_prompt", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ] ) def __lowerCAmelCase ( self : Optional[Any] ): torch.manual_seed(0 ) lowerCAmelCase__ : List[str] = 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, 6_4) ,class_embed_type='''simple_projection''' ,projection_class_embeddings_input_dim=3_2 ,class_embeddings_concat=lowercase_ ,) lowerCAmelCase__ : List[Any] = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule='''scaled_linear''' ,clip_sample=lowercase_ ,set_alpha_to_one=lowercase_ ,) torch.manual_seed(0 ) lowerCAmelCase__ : Any = AutoencoderKL( block_out_channels=[3_2, 6_4] ,in_channels=1 ,out_channels=1 ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,latent_channels=4 ,) torch.manual_seed(0 ) lowerCAmelCase__ : Dict = ClapTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=3_2 ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,projection_dim=3_2 ,) lowerCAmelCase__ : int = ClapTextModelWithProjection(lowercase_ ) lowerCAmelCase__ : Tuple = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' ,model_max_length=7_7 ) lowerCAmelCase__ : Union[str, Any] = SpeechTaHifiGanConfig( model_in_dim=8 ,sampling_rate=1_6_0_0_0 ,upsample_initial_channel=1_6 ,upsample_rates=[2, 2] ,upsample_kernel_sizes=[4, 4] ,resblock_kernel_sizes=[3, 7] ,resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] ,normalize_before=lowercase_ ,) lowerCAmelCase__ : Any = SpeechTaHifiGan(lowercase_ ) lowerCAmelCase__ : Optional[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''vocoder''': vocoder, } return components def __lowerCAmelCase ( self : str ,lowercase_ : Dict ,lowercase_ : Optional[Any]=0 ): if str(lowercase_ ).startswith('''mps''' ): lowerCAmelCase__ : Optional[Any] = torch.manual_seed(lowercase_ ) else: lowerCAmelCase__ : Union[str, Any] = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) lowerCAmelCase__ : List[str] = { '''prompt''': '''A hammer hitting a wooden surface''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, } return inputs def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ : Tuple = self.get_dummy_components() lowerCAmelCase__ : Optional[Any] = AudioLDMPipeline(**lowercase_ ) lowerCAmelCase__ : Optional[int] = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : List[Any] = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase__ : List[str] = audioldm_pipe(**lowercase_ ) lowerCAmelCase__ : str = output.audios[0] assert audio.ndim == 1 assert len(lowercase_ ) == 2_5_6 lowerCAmelCase__ : str = audio[:1_0] lowerCAmelCase__ : str = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : int ): lowerCAmelCase__ : Optional[Any] = self.get_dummy_components() lowerCAmelCase__ : Any = AudioLDMPipeline(**lowercase_ ) lowerCAmelCase__ : int = audioldm_pipe.to(lowercase_ ) lowerCAmelCase__ : Tuple = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : Tuple = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase__ : List[str] = 3 * [inputs['''prompt''']] # forward lowerCAmelCase__ : int = audioldm_pipe(**lowercase_ ) lowerCAmelCase__ : List[str] = output.audios[0] lowerCAmelCase__ : Union[str, Any] = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase__ : str = 3 * [inputs.pop('''prompt''' )] lowerCAmelCase__ : List[Any] = audioldm_pipe.tokenizer( lowercase_ ,padding='''max_length''' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=lowercase_ ,return_tensors='''pt''' ,) lowerCAmelCase__ : Tuple = text_inputs['''input_ids'''].to(lowercase_ ) lowerCAmelCase__ : List[Any] = audioldm_pipe.text_encoder( lowercase_ ,) lowerCAmelCase__ : Tuple = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state lowerCAmelCase__ : Tuple = F.normalize(lowercase_ ,dim=-1 ) lowerCAmelCase__ : List[Any] = prompt_embeds # forward lowerCAmelCase__ : Union[str, Any] = audioldm_pipe(**lowercase_ ) lowerCAmelCase__ : Any = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def __lowerCAmelCase ( self : str ): lowerCAmelCase__ : Union[str, Any] = self.get_dummy_components() lowerCAmelCase__ : List[Any] = AudioLDMPipeline(**lowercase_ ) lowerCAmelCase__ : List[str] = audioldm_pipe.to(lowercase_ ) lowerCAmelCase__ : Dict = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : str = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase__ : int = 3 * ['''this is a negative prompt'''] lowerCAmelCase__ : Any = negative_prompt lowerCAmelCase__ : int = 3 * [inputs['''prompt''']] # forward lowerCAmelCase__ : Tuple = audioldm_pipe(**lowercase_ ) lowerCAmelCase__ : List[str] = output.audios[0] lowerCAmelCase__ : Optional[Any] = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase__ : Optional[int] = 3 * [inputs.pop('''prompt''' )] lowerCAmelCase__ : Optional[Any] = [] for p in [prompt, negative_prompt]: lowerCAmelCase__ : int = audioldm_pipe.tokenizer( lowercase_ ,padding='''max_length''' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=lowercase_ ,return_tensors='''pt''' ,) lowerCAmelCase__ : Optional[Any] = text_inputs['''input_ids'''].to(lowercase_ ) lowerCAmelCase__ : Dict = audioldm_pipe.text_encoder( lowercase_ ,) lowerCAmelCase__ : Dict = text_embeds.text_embeds # additional L_2 normalization over each hidden-state lowerCAmelCase__ : Any = F.normalize(lowercase_ ,dim=-1 ) embeds.append(lowercase_ ) lowerCAmelCase__ ,lowerCAmelCase__ : int = embeds # forward lowerCAmelCase__ : List[str] = audioldm_pipe(**lowercase_ ) lowerCAmelCase__ : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def __lowerCAmelCase ( self : Optional[Any] ): lowerCAmelCase__ : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ : Optional[int] = self.get_dummy_components() lowerCAmelCase__ : Union[str, Any] = PNDMScheduler(skip_prk_steps=lowercase_ ) lowerCAmelCase__ : Optional[int] = AudioLDMPipeline(**lowercase_ ) lowerCAmelCase__ : List[str] = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : Dict = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase__ : Union[str, Any] = '''egg cracking''' lowerCAmelCase__ : Tuple = audioldm_pipe(**lowercase_ ,negative_prompt=lowercase_ ) lowerCAmelCase__ : List[Any] = output.audios[0] assert audio.ndim == 1 assert len(lowercase_ ) == 2_5_6 lowerCAmelCase__ : Any = audio[:1_0] lowerCAmelCase__ : List[Any] = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ : str = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ : Tuple = self.get_dummy_components() lowerCAmelCase__ : int = PNDMScheduler(skip_prk_steps=lowercase_ ) lowerCAmelCase__ : Union[str, Any] = AudioLDMPipeline(**lowercase_ ) lowerCAmelCase__ : Optional[int] = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : Optional[int] = '''A hammer hitting a wooden surface''' # test num_waveforms_per_prompt=1 (default) lowerCAmelCase__ : Dict = audioldm_pipe(lowercase_ ,num_inference_steps=2 ).audios assert audios.shape == (1, 2_5_6) # test num_waveforms_per_prompt=1 (default) for batch of prompts lowerCAmelCase__ : List[Any] = 2 lowerCAmelCase__ : Union[str, Any] = audioldm_pipe([prompt] * batch_size ,num_inference_steps=2 ).audios assert audios.shape == (batch_size, 2_5_6) # test num_waveforms_per_prompt for single prompt lowerCAmelCase__ : Dict = 2 lowerCAmelCase__ : int = audioldm_pipe(lowercase_ ,num_inference_steps=2 ,num_waveforms_per_prompt=lowercase_ ).audios assert audios.shape == (num_waveforms_per_prompt, 2_5_6) # test num_waveforms_per_prompt for batch of prompts lowerCAmelCase__ : Optional[int] = 2 lowerCAmelCase__ : List[Any] = audioldm_pipe( [prompt] * batch_size ,num_inference_steps=2 ,num_waveforms_per_prompt=lowercase_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_5_6) def __lowerCAmelCase ( self : Optional[Any] ): lowerCAmelCase__ : Optional[int] = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ : Optional[int] = self.get_dummy_components() lowerCAmelCase__ : Optional[Any] = AudioLDMPipeline(**lowercase_ ) lowerCAmelCase__ : List[Any] = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : Any = audioldm_pipe.vocoder.config.sampling_rate lowerCAmelCase__ : Any = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase__ : Dict = audioldm_pipe(audio_length_in_s=0.016 ,**lowercase_ ) lowerCAmelCase__ : Union[str, Any] = output.audios[0] assert audio.ndim == 1 assert len(lowercase_ ) / vocoder_sampling_rate == 0.016 lowerCAmelCase__ : Union[str, Any] = audioldm_pipe(audio_length_in_s=0.032 ,**lowercase_ ) lowerCAmelCase__ : Optional[int] = output.audios[0] assert audio.ndim == 1 assert len(lowercase_ ) / vocoder_sampling_rate == 0.032 def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ : int = self.get_dummy_components() lowerCAmelCase__ : Tuple = AudioLDMPipeline(**lowercase_ ) lowerCAmelCase__ : Optional[int] = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : str = ['''hey'''] lowerCAmelCase__ : str = audioldm_pipe(lowercase_ ,num_inference_steps=1 ) lowerCAmelCase__ : str = output.audios.shape assert audio_shape == (1, 2_5_6) lowerCAmelCase__ : Tuple = audioldm_pipe.vocoder.config config.model_in_dim *= 2 lowerCAmelCase__ : int = SpeechTaHifiGan(lowercase_ ).to(lowercase_ ) lowerCAmelCase__ : str = audioldm_pipe(lowercase_ ,num_inference_steps=1 ) lowerCAmelCase__ : Dict = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 2_5_6) def __lowerCAmelCase ( self : Any ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowercase_ ) def __lowerCAmelCase ( self : Dict ): self._test_inference_batch_single_identical(test_mean_pixel_difference=lowercase_ ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() ,reason='''XFormers attention is only available with CUDA and `xformers` installed''' ,) def __lowerCAmelCase ( self : Optional[Any] ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowercase_ ) @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : str ): super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : Any ,lowercase_ : Any ,lowercase_ : Union[str, Any]="cpu" ,lowercase_ : Any=torch.floataa ,lowercase_ : Tuple=0 ): lowerCAmelCase__ : str = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) lowerCAmelCase__ : str = np.random.RandomState(lowercase_ ).standard_normal((1, 8, 1_2_8, 1_6) ) lowerCAmelCase__ : str = torch.from_numpy(lowercase_ ).to(device=lowercase_ ,dtype=lowercase_ ) lowerCAmelCase__ : List[Any] = { '''prompt''': '''A hammer hitting a wooden surface''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 2.5, } return inputs def __lowerCAmelCase ( self : Dict ): lowerCAmelCase__ : Union[str, Any] = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) lowerCAmelCase__ : List[Any] = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : Union[str, Any] = self.get_inputs(lowercase_ ) lowerCAmelCase__ : Union[str, Any] = 2_5 lowerCAmelCase__ : Optional[Any] = audioldm_pipe(**lowercase_ ).audios[0] assert audio.ndim == 1 assert len(lowercase_ ) == 8_1_9_2_0 lowerCAmelCase__ : Optional[Any] = audio[7_7_2_3_0:7_7_2_4_0] lowerCAmelCase__ : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) lowerCAmelCase__ : List[str] = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1E-2 def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Optional[int] = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) lowerCAmelCase__ : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) lowerCAmelCase__ : str = audioldm_pipe.to(lowercase_ ) audioldm_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase__ : Optional[Any] = self.get_inputs(lowercase_ ) lowerCAmelCase__ : Union[str, Any] = audioldm_pipe(**lowercase_ ).audios[0] assert audio.ndim == 1 assert len(lowercase_ ) == 8_1_9_2_0 lowerCAmelCase__ : List[Any] = audio[2_7_7_8_0:2_7_7_9_0] lowerCAmelCase__ : Any = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) lowerCAmelCase__ : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3E-2
106
"""simple docstring""" from __future__ import annotations import requests def _snake_case ( snake_case__ : str ): A = F'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case__ ).json() def _snake_case ( snake_case__ : int = 10 ): A = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' A = requests.get(snake_case__ ).json()[:max_stories] return [get_hackernews_story(snake_case__ ) for story_id in story_ids] def _snake_case ( snake_case__ : int = 10 ): A = hackernews_top_stories(snake_case__ ) return "\n".join('* [{title}]({url})'.format(**snake_case__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
74
0
import qiskit def __magic_name__ ( A : int, A : int ): '''simple docstring''' a = qiskit.Aer.get_backend("aer_simulator" ) # Create a Quantum Circuit acting on the q register a = qiskit.QuantumCircuit(A, A ) # Map the quantum measurement to the classical bits circuit.measure([0], [0] ) # Execute the circuit on the simulator a = qiskit.execute(A, A, shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(A ) if __name__ == "__main__": print(F'''Total count for various states are: {single_qubit_measure(1, 1)}''')
107
"""simple docstring""" from string import ascii_uppercase _lowercase = {char: i for i, char in enumerate(ascii_uppercase)} _lowercase = dict(enumerate(ascii_uppercase)) def _snake_case ( snake_case__ : str , snake_case__ : str ): A = len(snake_case__ ) A = 0 while True: if x == i: A = 0 if len(snake_case__ ) == len(snake_case__ ): break key += key[i] i += 1 return key def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in message: if letter == " ": cipher_text += " " else: A = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _snake_case ( snake_case__ : str , snake_case__ : str ): A = '' A = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: A = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _snake_case ( ): A = 'THE GERMAN ATTACK' A = 'SECRET' A = generate_key(snake_case__ , snake_case__ ) A = cipher_text(snake_case__ , snake_case__ ) print(F'Encrypted Text = {s}' ) print(F'Original Text = {original_text(snake_case__ , snake_case__ )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
74
0
"""simple docstring""" from __future__ import annotations def a__ ( SCREAMING_SNAKE_CASE : list[int] ): '''simple docstring''' lowerCAmelCase : List[Any] = len(SCREAMING_SNAKE_CASE ) // 2 # choose the middle 3 elements lowerCAmelCase : Dict = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
108
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ) -> Optional[Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] ,model_result['ss'] ): A = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = 'sgugger/tiny-distilbert-classification' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,only_pretrain_model=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,torchscript=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,fpaa=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) # set architectures equal to `None` A = None A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' ,'Can\'t do half precision' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,fpaa=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,save_to_csv=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,inference_time_csv_file=os.path.join(A_ ,'inf_time.csv' ) ,train_memory_csv_file=os.path.join(A_ ,'train_mem.csv' ) ,inference_memory_csv_file=os.path.join(A_ ,'inf_mem.csv' ) ,train_time_csv_file=os.path.join(A_ ,'train_time.csv' ) ,env_info_csv_file=os.path.join(A_ ,'env.csv' ) ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) benchmark.run() self.assertTrue(Path(os.path.join(A_ ,'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'env.csv' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(A_ : Optional[int] ): self.assertTrue(hasattr(A_ ,'sequential' ) ) self.assertTrue(hasattr(A_ ,'cumulative' ) ) self.assertTrue(hasattr(A_ ,'current' ) ) self.assertTrue(hasattr(A_ ,'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,log_filename=os.path.join(A_ ,'log.txt' ) ,log_print=A_ ,trace_memory_line_by_line=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A_ ,'log.txt' ) ).exists() )
74
0
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time A: Optional[Any] = Lock() def _snake_case ( UpperCamelCase : Tuple , UpperCamelCase : Optional[int] , UpperCamelCase : List[str] , UpperCamelCase : int , UpperCamelCase : str , UpperCamelCase : Dict , UpperCamelCase : str ): global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(UpperCamelCase ) process_lock.release() # receive your right neighbor's value process_lock.acquire() UpperCAmelCase : Optional[Any] = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left UpperCAmelCase : List[Any] = min(UpperCamelCase , UpperCamelCase ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(UpperCamelCase ) process_lock.release() # receive your left neighbor's value process_lock.acquire() UpperCAmelCase : str = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right UpperCAmelCase : List[str] = max(UpperCamelCase , UpperCamelCase ) # after all swaps are performed, send the values back to main result_pipe[1].send(UpperCamelCase ) def _snake_case ( UpperCamelCase : Optional[int] ): UpperCAmelCase : Tuple = [] UpperCAmelCase : List[str] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop UpperCAmelCase : Optional[Any] = Pipe() UpperCAmelCase : Optional[int] = Pipe() process_array_.append( Process( target=UpperCamelCase , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) UpperCAmelCase : int = temp_rs UpperCAmelCase : Optional[Any] = temp_rr for i in range(1 , len(UpperCamelCase ) - 1 ): UpperCAmelCase : Optional[Any] = Pipe() UpperCAmelCase : Tuple = Pipe() process_array_.append( Process( target=UpperCamelCase , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) UpperCAmelCase : Optional[int] = temp_rs UpperCAmelCase : Optional[int] = temp_rr process_array_.append( Process( target=UpperCamelCase , args=( len(UpperCamelCase ) - 1, arr[len(UpperCamelCase ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(UpperCamelCase ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(UpperCamelCase ) ): UpperCAmelCase : str = result_pipe[p][0].recv() process_array_[p].join() return arr def _snake_case ( ): UpperCAmelCase : Dict = list(range(10 , 0 , -1 ) ) print("""Initial List""" ) print(*UpperCamelCase ) UpperCAmelCase : int = odd_even_transposition(UpperCamelCase ) print("""Sorted List\n""" ) print(*UpperCamelCase ) if __name__ == "__main__": main()
109
"""simple docstring""" # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _lowercase = re.compile(r'''^(?P<major>\d+)''' r'''\.(?P<minor>\d+)''' r'''\.(?P<patch>\d+)$''') @total_ordering @dataclass class lowerCAmelCase_ : '''simple docstring''' _lowerCamelCase: str _lowerCamelCase: Optional[str] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None _lowerCamelCase: Optional[Union[str, int]] = None def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: A , A , A = _str_to_version_tuple(self.version_str ) def __repr__( self : Optional[int] ) -> Dict: return F'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return self.major, self.minor, self.patch def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Tuple ) -> Union[str, Any]: if isinstance(A_ ,A_ ): return Version(A_ ) elif isinstance(A_ ,A_ ): return other raise TypeError(F'{other} (type {type(A_ )}) cannot be compared to version.' ) def __eq__( self : List[Any] ,A_ : Dict ) -> Any: try: A = self._validate_operand(A_ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : List[Any] ,A_ : Optional[int] ) -> Tuple: A = self._validate_operand(A_ ) return self.tuple < other.tuple def __hash__( self : Union[str, Any] ) -> Union[str, Any]: return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,A_ : List[str] ) -> List[str]: A = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.version_str def _snake_case ( snake_case__ : List[str] ): A = _VERSION_REG.match(snake_case__ ) if not res: raise ValueError(F'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(snake_case__ ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def _snake_case ( snake_case__ : str ): return ".".join(str(snake_case__ ) for v in version_tuple )
74
0
from math import isqrt, loga def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowercase__ = False return [i for i in range(2 , SCREAMING_SNAKE_CASE ) if is_prime[i]] def _a ( SCREAMING_SNAKE_CASE = 80_08_00 , SCREAMING_SNAKE_CASE = 80_08_00 ): """simple docstring""" lowercase__ = degree * loga(SCREAMING_SNAKE_CASE ) lowercase__ = int(SCREAMING_SNAKE_CASE ) lowercase__ = calculate_prime_numbers(SCREAMING_SNAKE_CASE ) lowercase__ = 0 lowercase__ = 0 lowercase__ = len(SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
110
"""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 _lowercase = NewType('''DataClass''', Any) _lowercase = NewType('''DataClassType''', Any) def _snake_case ( snake_case__ : Tuple ): if isinstance(snake_case__ , snake_case__ ): 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 _snake_case ( snake_case__ : list ): A = {str(snake_case__ ): choice for choice in choices} return lambda snake_case__ : str_to_choice.get(snake_case__ , snake_case__ ) def _snake_case ( *, snake_case__ : Union[str, List[str]] = None , snake_case__ : str = None , snake_case__ : Any = dataclasses.MISSING , snake_case__ : Callable[[], Any] = dataclasses.MISSING , snake_case__ : dict = None , **snake_case__ : Any , ): if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls A = {} if aliases is not None: A = aliases if help is not None: A = help return dataclasses.field(metadata=snake_case__ , default=snake_case__ , default_factory=snake_case__ , **snake_case__ ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Iterable[DataClassType] def __init__( self : List[str] ,A_ : Union[DataClassType, Iterable[DataClassType]] ,**A_ : Any ) -> Optional[int]: # To make the default appear when using --help if "formatter_class" not in kwargs: A = ArgumentDefaultsHelpFormatter super().__init__(**A_ ) if dataclasses.is_dataclass(A_ ): A = [dataclass_types] A = list(A_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( A_ : ArgumentParser ,A_ : dataclasses.Field ) -> Optional[Any]: A = F'--{field.name}' A = 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 ,A_ ): raise RuntimeError( 'Unresolved type detected, which should have been done with the help of ' '`typing.get_type_hints` method by default' ) A = kwargs.pop('aliases' ,[] ) if isinstance(A_ ,A_ ): A = [aliases] A = getattr(field.type ,'__origin__' ,field.type ) if origin_type is Union or (hasattr(A_ ,'UnionType' ) and isinstance(A_ ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A_ ) 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(A_ ) not in field.type.__args__: # filter `str` in Union A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] A = getattr(field.type ,'__origin__' ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) A = ( field.type.__args__[0] if isinstance(A_ ,field.type.__args__[1] ) else field.type.__args__[1] ) A = 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) A = {} if origin_type is Literal or (isinstance(field.type ,A_ ) and issubclass(field.type ,A_ )): if origin_type is Literal: A = field.type.__args__ else: A = [x.value for x in field.type] A = make_choice_type_function(kwargs['choices'] ) if field.default is not dataclasses.MISSING: A = field.default else: A = 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 A = copy(A_ ) # Hack because type=bool in argparse does not behave as we want. A = 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. A = 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 A = default # This tells argparse we accept 0 or 1 value after --field_name A = '?' # This is the value that will get picked if we do --field_name (without value) A = True elif isclass(A_ ) and issubclass(A_ ,A_ ): A = field.type.__args__[0] A = '+' if field.default_factory is not dataclasses.MISSING: A = field.default_factory() elif field.default is dataclasses.MISSING: A = True else: A = field.type if field.default is not dataclasses.MISSING: A = field.default elif field.default_factory is not dataclasses.MISSING: A = field.default_factory() else: A = True parser.add_argument(A_ ,*A_ ,**A_ ) # 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]): A = False parser.add_argument(F'--no_{field.name}' ,action='store_false' ,dest=field.name ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : DataClassType ) -> List[Any]: if hasattr(A_ ,'_argument_group_name' ): A = self.add_argument_group(dtype._argument_group_name ) else: A = self try: A = get_type_hints(A_ ) 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(A_ ): A = '.'.join(map(A_ ,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(A_ ): if not field.init: continue A = type_hints[field.name] self._parse_dataclass_field(A_ ,A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Any=None ,A_ : int=False ,A_ : Any=True ,A_ : List[str]=None ,A_ : Union[str, Any]=None ,) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): A = [] if args_filename: args_files.append(Path(A_ ) ) 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 A = ArgumentParser() args_file_parser.add_argument(A_ ,type=A_ ,action='append' ) # Use only remaining args for further parsing (remove the args_file_flag) A , A = args_file_parser.parse_known_args(args=A_ ) A = vars(A_ ).get(args_file_flag.lstrip('-' ) ,A_ ) if cmd_args_file_paths: args_files.extend([Path(A_ ) for p in cmd_args_file_paths] ) A = [] 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 A = file_args + args if args is not None else file_args + sys.argv[1:] A , A = self.parse_known_args(args=A_ ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in vars(A_ ).items() if k in keys} for k in keys: delattr(A_ ,A_ ) A = dtype(**A_ ) outputs.append(A_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A_ ) 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 _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Dict[str, Any] ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = set(args.keys() ) A = [] for dtype in self.dataclass_types: A = {f.name for f in dataclasses.fields(A_ ) if f.init} A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) A = dtype(**A_ ) outputs.append(A_ ) if not allow_extra_keys and unused_keys: raise ValueError(F'Some keys are not used by the HfArgumentParser: {sorted(A_ )}' ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: with open(Path(A_ ) ,encoding='utf-8' ) as open_json_file: A = json.loads(open_json_file.read() ) A = self.parse_dict(A_ ,allow_extra_keys=A_ ) return tuple(A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : str ,A_ : bool = False ) -> Tuple[DataClass, ...]: A = self.parse_dict(yaml.safe_load(Path(A_ ).read_text() ) ,allow_extra_keys=A_ ) return tuple(A_ )
74
0
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def UpperCAmelCase__ ( _A : Dict ): '''simple docstring''' a__ =[ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(snake_case__ , snake_case__ ) def UpperCAmelCase__ ( _A : int ): '''simple docstring''' a__, a__ =emb.weight.shape a__ =nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) a__ =emb.weight.data return lin_layer def UpperCAmelCase__ ( _A : List[str] , _A : Any="facebook/mbart-large-en-ro" , _A : Optional[int]=False , _A : List[str]=False ): '''simple docstring''' a__ =torch.load(snake_case__ , map_location='''cpu''' )['''model'''] remove_ignore_keys_(snake_case__ ) a__ =state_dict['''encoder.embed_tokens.weight'''].shape[0] a__ =MBartConfig.from_pretrained(snake_case__ , vocab_size=snake_case__ ) if mbart_aa and finetuned: a__ ='''relu''' a__ =state_dict['''decoder.embed_tokens.weight'''] a__ =MBartForConditionalGeneration(snake_case__ ) model.model.load_state_dict(snake_case__ ) if finetuned: a__ =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)
188
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase = 16 _lowercase = 32 def _snake_case ( snake_case__ : Accelerator , snake_case__ : int = 16 , snake_case__ : str = "bert-base-cased" ): A = AutoTokenizer.from_pretrained(snake_case__ ) A = load_dataset('glue' , 'mrpc' ) def tokenize_function(snake_case__ : Dict ): # max_length=None => use the model max length (it's actually the default) A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=snake_case__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(snake_case__ : int ): # 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(snake_case__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(snake_case__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. A = DataLoader( tokenized_datasets['train'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A = DataLoader( tokenized_datasets['validation'] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader def _snake_case ( snake_case__ : Optional[int] , snake_case__ : Optional[int] ): # Initialize accelerator A = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A = config['lr'] A = int(config['num_epochs'] ) A = int(config['seed'] ) A = int(config['batch_size'] ) A = args.model_name_or_path set_seed(snake_case__ ) A , A = get_dataloaders(snake_case__ , snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A = AutoModelForSequenceClassification.from_pretrained(snake_case__ , return_dict=snake_case__ ) # Instantiate optimizer A = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A = optimizer_cls(params=model.parameters() , lr=snake_case__ ) if accelerator.state.deepspeed_plugin is not None: A = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A = 1 A = (len(snake_case__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=0 , num_training_steps=snake_case__ , ) else: A = DummyScheduler(snake_case__ , total_num_steps=snake_case__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A , A , A , A , A = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # We need to keep track of how many total steps we have iterated over A = 0 # We also need to keep track of the stating epoch so files are named properly A = 0 # Now we train the model A = evaluate.load('glue' , 'mrpc' ) A = 0 A = {} for epoch in range(snake_case__ , snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): A = model(**snake_case__ ) A = outputs.loss A = loss / gradient_accumulation_steps accelerator.backward(snake_case__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() A = 0 for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A = model(**snake_case__ ) A = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case__ ) - 1: A = predictions[: len(eval_dataloader.dataset ) - samples_seen] A = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) A = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: A = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(snake_case__ , snake_case__ ) def _snake_case ( ): A = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=snake_case__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=snake_case__ , ) parser.add_argument( '--output_dir' , type=snake_case__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=snake_case__ , default=snake_case__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=snake_case__ , default=3 , help='Number of train epochs.' , ) A = parser.parse_args() A = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
74
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase : Tuple = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[int] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
267
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A = ids_tensor([self.batch_size] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs 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 : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
0
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =FlaxMTaForConditionalGeneration.from_pretrained('google/mt5-small' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('google/mt5-small' ) SCREAMING_SNAKE_CASE =tokenizer('Hello there' ,return_tensors='np' ).input_ids SCREAMING_SNAKE_CASE =tokenizer('Hi I am' ,return_tensors='np' ).input_ids SCREAMING_SNAKE_CASE =shift_tokens_right(A_ ,model.config.pad_token_id ,model.config.decoder_start_token_id ) SCREAMING_SNAKE_CASE =model(A_ ,decoder_input_ids=A_ ).logits SCREAMING_SNAKE_CASE =optax.softmax_cross_entropy(A_ ,onehot(A_ ,logits.shape[-1] ) ).mean() SCREAMING_SNAKE_CASE =-(labels.shape[-1] * loss.item()) SCREAMING_SNAKE_CASE =-84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
334
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase = logging.get_logger(__name__) @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[int] = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : int ,**A_ : Any ) -> Any: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: A = deprecated_arg[3:] A = not kwargs.pop(A_ ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) A = kwargs.pop('tpu_name' ,self.tpu_name ) A = kwargs.pop('device_idx' ,self.device_idx ) A = kwargs.pop('eager_mode' ,self.eager_mode ) A = kwargs.pop('use_xla' ,self.use_xla ) super().__init__(**A_ ) _lowerCamelCase: str = field( default=_lowercase , metadata={'''help''': '''Name of TPU'''} , ) _lowerCamelCase: int = field( default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , ) _lowerCamelCase: bool = field(default=_lowercase , metadata={'''help''': '''Benchmark models in eager model.'''} ) _lowerCamelCase: bool = field( default=_lowercase , metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' } , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) A = None if self.tpu: try: if self.tpu_name: A = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: A = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: A = None return tpu @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self ,['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) A = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,'GPU' ) A = tf.distribute.OneDeviceStrategy(device=F'/gpu:{self.device_idx}' ) else: tf.config.set_visible_devices([] ,'GPU' ) # disable GPU A = tf.distribute.OneDeviceStrategy(device=F'/cpu:{self.device_idx}' ) return strategy @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> bool: requires_backends(self ,['tf'] ) return self._setup_tpu is not None @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> "tf.distribute.Strategy": requires_backends(self ,['tf'] ) return self._setup_strategy @property def _SCREAMING_SNAKE_CASE ( self : int ) -> str: requires_backends(self ,['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: requires_backends(self ,['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _SCREAMING_SNAKE_CASE ( self : str ) -> bool: return self.n_gpu > 0
74
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCamelCase = "▁" __lowerCamelCase = {"vocab_file": "spiece.model"} __lowerCamelCase = { "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"} } __lowerCamelCase = { "google/pegasus-xsum": 5_12, } __lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase__( _lowercase ): lowerCAmelCase__ : List[str] = VOCAB_FILES_NAMES lowerCAmelCase__ : Optional[Any] = VOCAB_FILES_NAMES lowerCAmelCase__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : str = ['''input_ids''', '''attention_mask'''] def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase="<pad>" ,__UpperCAmelCase="</s>" ,__UpperCAmelCase="<unk>" ,__UpperCAmelCase="<mask_2>" ,__UpperCAmelCase="<mask_1>" ,__UpperCAmelCase=None ,__UpperCAmelCase=1_03 ,__UpperCAmelCase = None ,**__UpperCAmelCase ,) -> None: A__ = offset if additional_special_tokens is not None: if not isinstance(A_ ,A_ ): raise TypeError( f'''additional_special_tokens should be of type {type(A_ )}, but is''' f''' {type(A_ )}''' ) A__ = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(A_ ) ,self.offset - 1 ) ] if len(set(A_ ) ) != len(A_ ): raise ValueError( 'Please make sure that the provided additional_special_tokens do not contain an incorrectly' f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) A__ = additional_special_tokens_extended else: A__ = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 ,self.offset )] A__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=A_ ,unk_token=A_ ,mask_token=A_ ,pad_token=A_ ,mask_token_sent=A_ ,offset=A_ ,additional_special_tokens=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A__ = mask_token_sent A__ = vocab_file A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) # add special tokens to encoder dict A__ = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 ,self.offset - 1 )} ) A__ = {v: k for k, v in self.encoder.items()} @property def snake_case__ ( self ) -> int: return len(self.sp_model ) + self.offset def snake_case__ ( self ) -> Dict[str, int]: A__ = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Optional[int]: A__ = self.__dict__.copy() A__ = None return state def __setstate__( self ,__UpperCAmelCase ) -> List[str]: A__ = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A__ = {} A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def snake_case__ ( self ,__UpperCAmelCase ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def snake_case__ ( self ,__UpperCAmelCase ) -> int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] A__ = self.sp_model.piece_to_id(A_ ) return sp_id + self.offset def snake_case__ ( self ,__UpperCAmelCase ) -> str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: A__ = self.sp_model.IdToPiece(index - self.offset ) return token def snake_case__ ( self ,__UpperCAmelCase ) -> Any: A__ = [] A__ = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A_ ) + token A__ = [] else: current_sub_tokens.append(A_ ) out_string += self.sp_model.decode(A_ ) return out_string.strip() def snake_case__ ( self ,__UpperCAmelCase=False ) -> Optional[Any]: return 1 def snake_case__ ( self ,__UpperCAmelCase ) -> Optional[int]: A__ = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ,__UpperCAmelCase = False ) -> List[int]: if already_has_special_tokens: return self._special_token_mask(A_ ) elif token_ids_a is None: return self._special_token_mask(A_ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return A__ = os.path.join( A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A__ = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
221
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowercase = logging.get_logger(__name__) _lowercase = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = '''dpt''' def __init__( self : str ,A_ : Tuple=768 ,A_ : int=12 ,A_ : Optional[int]=12 ,A_ : Optional[int]=3072 ,A_ : List[str]="gelu" ,A_ : str=0.0 ,A_ : int=0.0 ,A_ : str=0.02 ,A_ : str=1e-12 ,A_ : str=384 ,A_ : Dict=16 ,A_ : Union[str, Any]=3 ,A_ : Dict=False ,A_ : Any=True ,A_ : Optional[int]=[2, 5, 8, 11] ,A_ : Optional[Any]="project" ,A_ : Tuple=[4, 2, 1, 0.5] ,A_ : int=[96, 192, 384, 768] ,A_ : int=256 ,A_ : str=-1 ,A_ : Optional[int]=False ,A_ : Optional[int]=True ,A_ : Union[str, Any]=0.4 ,A_ : Union[str, Any]=255 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=[1, 1024, 24, 24] ,A_ : List[str]=[0, 1] ,A_ : List[Any]=None ,**A_ : Tuple ,) -> Union[str, Any]: super().__init__(**A_ ) A = hidden_size A = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) A = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): logger.info('Initializing the config with a `BiT` backbone.' ) A = BitConfig(**A_ ) elif isinstance(A_ ,A_ ): A = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) A = backbone_featmap_shape A = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: A = None A = None A = [] A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) A = readout_type A = reassemble_factors A = neck_hidden_sizes A = fusion_hidden_size A = head_in_index A = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) A = use_auxiliary_head A = auxiliary_loss_weight A = semantic_loss_ignore_index A = semantic_classifier_dropout def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: A = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: A = self.backbone_config.to_dict() A = self.__class__.model_type return output
74
0
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Any = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } SCREAMING_SNAKE_CASE : Optional[Any] = { """vocab_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json""" }, """merges_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt""" }, """tokenizer_config_file""": { """facebook/blenderbot_small-90M""": ( """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json""" ) }, } SCREAMING_SNAKE_CASE : Union[str, Any] = { """facebook/blenderbot_small-90M""": 512, } class _UpperCAmelCase ( _lowercase ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =BlenderbotSmallTokenizer def __init__(self , a_=None , a_=None , a_="<|endoftext|>" , a_="<|endoftext|>" , a_="<|endoftext|>" , a_=False , a_=True , **a_ , ): '''simple docstring''' super().__init__( ByteLevelBPETokenizer( vocab=A_ , merges=A_ , add_prefix_space=A_ , trim_offsets=A_ , ) , bos_token=A_ , eos_token=A_ , unk_token=A_ , **A_ , ) __snake_case : Tuple = add_prefix_space def SCREAMING_SNAKE_CASE (self , a_ , a_=None ): '''simple docstring''' __snake_case : Optional[int] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE (self , a_ , a_ = None ): '''simple docstring''' __snake_case : List[str] = [self.sep_token_id] __snake_case : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
102
"""simple docstring""" from __future__ import annotations import math _lowercase = '''2020.9.26''' _lowercase = '''xcodz-dot, cclaus, dhruvmanila''' def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : float ): if not all(isinstance(snake_case__ , (float, int) ) for val in locals().values() ): A = F'Input values must either be float or int: {list(locals().values() )}' raise TypeError(snake_case__ ) A = ((x * distance) / (z + distance)) * scale A = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _snake_case ( snake_case__ : float , snake_case__ : float , snake_case__ : float , snake_case__ : str , snake_case__ : float ): if not isinstance(snake_case__ , snake_case__ ): raise TypeError('Axis must be a str' ) A = locals() del input_variables["axis"] if not all(isinstance(snake_case__ , (float, int) ) for val in input_variables.values() ): A = ( 'Input values except axis must either be float or int: ' F'{list(input_variables.values() )}' ) raise TypeError(snake_case__ ) A = (angle % 360) / 450 * 180 / math.pi if axis == "z": A = x * math.cos(snake_case__ ) - y * math.sin(snake_case__ ) A = y * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = z elif axis == "x": A = y * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + y * math.sin(snake_case__ ) A = x elif axis == "y": A = x * math.cos(snake_case__ ) - z * math.sin(snake_case__ ) A = z * math.cos(snake_case__ ) + x * math.sin(snake_case__ ) A = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""") print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")
74
0
from __future__ import annotations __lowercase = 1.6021e-19 # units = C def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ): '''simple docstring''' if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif conductivity < 0: raise ValueError('''Conductivity cannot be negative''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative''' ) elif mobility < 0: raise ValueError('''mobility cannot be negative''' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
43
"""simple docstring""" class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int ,A_ : int ) -> Union[str, Any]: A = n A = [None] * self.n A = 0 # index of the first element A = 0 A = 0 def __len__( self : int ) -> int: return self.size def _SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.size == 0 def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: return False if self.is_empty() else self.array[self.front] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[Any] ) -> int: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) A = data A = (self.rear + 1) % self.n self.size += 1 return self def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) A = self.array[self.front] A = None A = (self.front + 1) % self.n self.size -= 1 return temp
74
0
def _a ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return number | (1 << position) def _a ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return number & ~(1 << position) def _a ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return number ^ (1 << position) def _a ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return ((number >> position) & 1) == 1 def _a ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
146
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] ,*A_ : List[str] ,**A_ : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' ,A_ ,) super().__init__(*A_ ,**A_ )
74
0
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[str] ): """simple docstring""" UpperCAmelCase__ = """""" UpperCAmelCase__ = """""" UpperCAmelCase__ = [] UpperCAmelCase__ = 0 UpperCAmelCase__ = 2_56 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 def SCREAMING_SNAKE_CASE__ ( self : str , _UpperCAmelCase : List[str] ): """simple docstring""" UpperCAmelCase__ = cva.imread(A_ , 0 ) UpperCAmelCase__ = copy.deepcopy(self.img ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label="""x""" ) UpperCAmelCase__ = np.sum(A_ ) for i in range(len(A_ ) ): UpperCAmelCase__ = x[i] / self.k self.sk += prk UpperCAmelCase__ = (self.L - 1) * self.sk if self.rem != 0: UpperCAmelCase__ = int(last % last ) UpperCAmelCase__ = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(A_ ) UpperCAmelCase__ = int(np.ma.count(self.img ) / self.img[1].size ) UpperCAmelCase__ = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCAmelCase__ = self.img[j][i] if num != self.last_list[num]: UpperCAmelCase__ = self.last_list[num] cva.imwrite("""output_data/output.jpg""" , self.img ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" cva.imshow("""Output-Image""" , self.img ) cva.imshow("""Input-Image""" , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": UpperCAmelCase_ = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') UpperCAmelCase_ = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
346
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''gpt_bigcode''' _lowerCamelCase: List[Any] = ['''past_key_values'''] _lowerCamelCase: int = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Optional[int] ,A_ : Dict=5_0257 ,A_ : Union[str, Any]=1024 ,A_ : str=768 ,A_ : Any=12 ,A_ : Any=12 ,A_ : Optional[int]=None ,A_ : Any="gelu_pytorch_tanh" ,A_ : List[str]=0.1 ,A_ : Optional[int]=0.1 ,A_ : List[str]=0.1 ,A_ : Tuple=1e-5 ,A_ : Optional[int]=0.02 ,A_ : List[str]=True ,A_ : Optional[Any]=True ,A_ : List[Any]=5_0256 ,A_ : Union[str, Any]=5_0256 ,A_ : int=True ,A_ : Optional[Any]=True ,A_ : Dict=True ,**A_ : Union[str, Any] ,) -> Union[str, Any]: A = vocab_size A = n_positions A = n_embd A = n_layer A = n_head A = n_inner A = activation_function A = resid_pdrop A = embd_pdrop A = attn_pdrop A = layer_norm_epsilon A = initializer_range A = scale_attn_weights A = use_cache A = attention_softmax_in_fpaa A = scale_attention_softmax_in_fpaa A = multi_query A = bos_token_id A = eos_token_id super().__init__(bos_token_id=A_ ,eos_token_id=A_ ,**A_ )
74
0
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/xprophetnet-large-wiki100-cased': ( 'https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json' ), } class snake_case ( _lowercase ): '''simple docstring''' A_ : int = '''xlm-prophetnet''' A_ : List[str] = ['''past_key_values'''] A_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Tuple, _lowerCamelCase : Optional[float] = 0.1, _lowerCamelCase : Optional[Union[str, Callable]] = "gelu", _lowerCamelCase : Optional[int] = 3_05_22, _lowerCamelCase : Optional[int] = 10_24, _lowerCamelCase : Optional[int] = 40_96, _lowerCamelCase : Optional[int] = 12, _lowerCamelCase : Optional[int] = 16, _lowerCamelCase : Optional[int] = 40_96, _lowerCamelCase : Optional[int] = 12, _lowerCamelCase : Optional[int] = 16, _lowerCamelCase : Optional[float] = 0.1, _lowerCamelCase : Optional[float] = 0.1, _lowerCamelCase : Optional[int] = 5_12, _lowerCamelCase : Optional[float] = 0.02, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[int] = 0, _lowerCamelCase : Optional[int] = 2, _lowerCamelCase : Optional[int] = 32, _lowerCamelCase : Optional[int] = 1_28, _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 : List[str], ): '''simple docstring''' __A = vocab_size __A = hidden_size __A = encoder_ffn_dim __A = num_encoder_layers __A = num_encoder_attention_heads __A = decoder_ffn_dim __A = num_decoder_layers __A = num_decoder_attention_heads __A = max_position_embeddings __A = init_std # Normal(0, this parameter) __A = activation_function # parameters for xlmprophetnet __A = ngram __A = num_buckets __A = relative_max_distance __A = disable_ngram_loss __A = eps # 3 Types of Dropout __A = attention_dropout __A = activation_dropout __A = dropout __A = use_cache super().__init__( pad_token_id=A_, bos_token_id=A_, eos_token_id=A_, is_encoder_decoder=A_, add_cross_attention=A_, decoder_start_token_id=A_, **A_, ) @property def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : Any ): '''simple docstring''' raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
266
"""simple docstring""" import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed _lowercase = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""): from run_translation import main # noqa set_seed(42) _lowercase = '''sshleifer/student_marian_en_ro_6_1''' _lowercase = '''sshleifer/tiny-mbart''' @require_torch class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Union[str, Any]=False ,A_ : Optional[int]=None ,A_ : List[str]=True ,A_ : Tuple=True ,A_ : Union[str, Any]=True ,A_ : List[str]=True ,) -> Tuple: A = self.run_trainer( eval_steps=1 ,max_len=12 ,model_name=A_ ,num_train_epochs=1 ,distributed=A_ ,extra_args_str=A_ ,predict_with_generate=A_ ,do_train=A_ ,do_eval=A_ ,do_predict=A_ ,) A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history if not do_eval: return A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats A = eval_metrics[-1] assert isinstance(last_step_stats['eval_bleu'] ,A_ ) assert not math.isnan(float(last_step_stats['eval_loss'] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict: self.run_seqaseq_quick() @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> int: self.run_seqaseq_quick(distributed=A_ ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp simple --fp16' ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2' ,predict_with_generate=A_ ) @unittest.skip('Requires an update of the env running those tests' ) @require_torch_multi_gpu @require_fairscale def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.run_seqaseq_quick( distributed=A_ ,extra_args_str='--sharded_ddp zero_dp_2 --fp16' ,predict_with_generate=A_ ) @require_apex @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A_ ,extra_args_str='--fp16 --fp16_backend=apex' ) @parameterized.expand(['base', 'low', 'high', 'mixed'] ) @require_torch_multi_gpu def _SCREAMING_SNAKE_CASE ( self : str ,A_ : Dict ) -> List[str]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout A = { # test with the default log_level - should be info and thus log info once 'base': {'extra_args_str': '', 'n_matches': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes 'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica 'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1}, # test with high log_level and log_level_replica - should be quiet on all processes 'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0}, } A = experiments[experiment_id] A = {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False} A = 'Running training' with CaptureStderr() as cl: self.run_seqaseq_quick(**A_ ,extra_args_str=data['extra_args_str'] ) A = len(re.findall(A_ ,cl.err ) ) self.assertEqual(A_ ,data['n_matches'] ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: A = self.run_trainer( eval_steps=2 ,max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=10 ,distributed=A_ ,) # Check metrics A = TrainerState.load_from_json(os.path.join(A_ ,'trainer_state.json' ) ).log_history A = [log for log in logs if 'eval_loss' in log.keys()] A = eval_metrics[0] A = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['eval_bleu'] ,A_ ) # test if do_predict saves generations and metrics A = os.listdir(A_ ) A = {os.path.basename(A_ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: from transformers.training_args import OptimizerNames def train_and_return_metrics(A_ : str ) -> Tuple[int, float]: A = '--skip_memory_metrics 0' A = self.run_trainer( max_len=128 ,model_name=A_ ,learning_rate=3e-4 ,num_train_epochs=1 ,optim=A_ ,distributed=A_ ,extra_args_str=A_ ,do_eval=A_ ,do_predict=A_ ,n_gpus_to_use=1 ,) # Check metrics A = TrainerState.load_from_json(Path(A_ ,'trainer_state.json' ) ).log_history A = int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20 ) A = int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20 ) A = logs[0]['train_loss'] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) A , A , A = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) A = gpu_alloc_mem_orig - gpu_alloc_mem_bnb A = gpu_peak_mem_orig + gpu_alloc_mem_orig A = gpu_peak_mem_bnb + gpu_alloc_mem_bnb A = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings A = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A_ ,A_ ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and' F' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB' ,) self.assertGreater( A_ ,A_ ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got' F' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and' F' gpu_total_mem_bnb={gpu_total_mem_bnb}MB' ,) self.assertEqual( A_ ,A_ ,F'loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}' ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : str ,A_ : int ,A_ : float = 3e-3 ,A_ : str = "adafactor" ,A_ : bool = False ,A_ : str = None ,A_ : int = 0 ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : bool = True ,A_ : int = None ,) -> Dict: A = self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro' A = self.get_auto_remove_tmp_dir() A = F'\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A_ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A_ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '.split() A = F'\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A_ )}\n '.split() A = '\n --do_predict\n '.split() A = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'--optim {optim}'.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: A = get_gpu_count() A = get_torch_dist_unique_port() A = F'\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '.split() A = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A_ ,env=self.get_env() ) else: A = ['run_translation.py'] + args with patch.object(A_ ,'argv' ,A_ ): main() return output_dir
74
0
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 a__ ( _lowercase , _lowercase ): """simple docstring""" __lowerCamelCase = 1 @register_to_config def __init__( self , lowercase=2000 , lowercase=0.1 , lowercase=20 , lowercase=1e-3 ) -> Dict: '''simple docstring''' A__ = None A__ = None A__ = None def UpperCamelCase ( self , lowercase , lowercase = None ) -> Optional[int]: '''simple docstring''' A__ = torch.linspace(1 , self.config.sampling_eps , A_ , device=A_ ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase=None ) -> Tuple: '''simple docstring''' 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 A__ = ( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) A__ = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) A__ = std.flatten() while len(std.shape ) < len(score.shape ): A__ = std.unsqueeze(-1 ) A__ = -score / std # compute A__ = -1.0 / len(self.timesteps ) A__ = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) A__ = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): A__ = beta_t.unsqueeze(-1 ) A__ = -0.5 * beta_t * x A__ = torch.sqrt(A_ ) A__ = drift - diffusion**2 * score A__ = x + drift * dt # add noise A__ = randn_tensor(x.shape , layout=x.layout , generator=A_ , device=x.device , dtype=x.dtype ) A__ = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self ) -> str: '''simple docstring''' return self.config.num_train_timesteps
68
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = '''deit''' def __init__( self : int ,A_ : Optional[Any]=768 ,A_ : Union[str, Any]=12 ,A_ : Dict=12 ,A_ : int=3072 ,A_ : Optional[Any]="gelu" ,A_ : Dict=0.0 ,A_ : Any=0.0 ,A_ : str=0.02 ,A_ : Tuple=1e-12 ,A_ : Union[str, Any]=224 ,A_ : Optional[Any]=16 ,A_ : List[Any]=3 ,A_ : Optional[Any]=True ,A_ : Optional[int]=16 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(**A_ ) A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = initializer_range A = layer_norm_eps A = image_size A = patch_size A = num_channels A = qkv_bias A = encoder_stride class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: int = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> float: return 1e-4
74
0